Why wont this code compile?
package main
const a = 1.000001
const base = 0
const b = a+base
func main() {
f(b)
}
func f(int) {}
$ go run a.go
# command-line-arguments
./a.go:4: constant 1 truncated to integer
It's saying that 1 is truncated? Or that 1 cannot be truncated? Which 1 is it talking about?
Someone answered the above code doesn't compile because b is a float64. But then why does this compile:
package main
import "fmt"
const a = 1.000001
const b = a-0.000001
func main() {
fmt.Printf("%T %v\n",a,a)
fmt.Printf("%T %v\n",b,b)
f(b)
}
func f(int) {}
$ go run a.go
float64 1.000001
float64 1
? b is a float64 here, but it can be passed to f.
Disclaimer: I do not have any experience with Go, but the below answer is based on general principles related to data types.
Your function
ftakes an input parameter of typeint, but the actual value that you pass to it i.e.bhas a floating point value based on your code. That will cause truncation of the floating point value to an integer value, as the error message states.I believe you could fix this issue by changing your function signature to take a floating type value as the input parameter i.e.
Demo in Go
To compare this to a language I am familiar with (C#), you can look at the below code:
Using the
varkeyword, we do not explicitly makeaandbvariables of datatypedouble. However, because floating-point values are being assigned to them, their type is inferred to bedouble. Now if you define the methodfas taking an input parameter of datatypeintand then pass inaorb. it will give you an error. However, if you change the method to take adoublevalue instead ofint, your code will compile without issue.Demo in C#