Dog*_*Dog 3 types go weak-typing
为什么这个代码不会编译?
package main
const a = 1.000001
const base = 0
const b = a+base
func main() {
f(b)
}
func f(int) {}
Run Code Online (Sandbox Code Playgroud)
$ go run a.go
# command-line-arguments
./a.go:4: constant 1 truncated to integer
Run Code Online (Sandbox Code Playgroud)
这是说1被截断了?或者1不能被截断?它在谈论哪一个?
有人回答上面的代码没有编译因为b是float64.但是为什么这会编译:
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) {}
Run Code Online (Sandbox Code Playgroud)
$ go run a.go
float64 1.000001
float64 1
Run Code Online (Sandbox Code Playgroud)
?b是一个float64在这里,但它可以传递给f.
从介绍
Go是一种静态类型语言,不允许混合数字类型的操作.您不能将float64添加到int,甚至将int32添加到int.写1e6*time.Second或math.Exp(1)或甚至1 <<('\ t'+ 2.0)是合法的.在Go中,常量与变量不同,其行为与常规数字非常相似.这篇文章解释了为什么会这样,它意味着什么.
TLDR - 常量在Go中是无类型的.它们的类型只在最后时刻结晶.
这解释了你上面的问题.特定
func f(int) {}
Run Code Online (Sandbox Code Playgroud)
然后
f(1) // ok
f(1.000) // OK
f(1.0E6) // OK
f(1.0001) // BAD
Run Code Online (Sandbox Code Playgroud)