http://tour.golang.org/ 中的 “Numeric Constants” 说:“An untyped constant takes the type needed by its context.” ,到底是什么意思? 常量的类型在声明时确定还是在调用常量时,类型才确定?具体调试例子如下:
package main
import "fmt"
const (
Big = 1 << 100
Small = Big >> 99
)
func needInt(x int) int { return x*10 + 1 }
func needFloat(x float64) float64 {
return x * 0.1
}
func main() {
fmt.Println(needInt(Small))
fmt.Println(needFloat(Small))
fmt.Println(needFloat(Big))
fmt.Printf(“%T\n", Small)
}
运行此代码,程序输出显示 Small 为 int 类型,但是 needFloat 函数的输入为 float64 类型,int 类型可以直接赋值给 float64 类型么? go 语言不同类型的值互相赋值时,语言规范要求必须显示转换,但此处并没有显示转换!难道 Small 的类型会变化,在 needInt(Small) 和 fmt.Printf(“%T\n", Small) 中,Small 为 int 类型,在 needFloat(Small) 中,Small 为 float64 类型?
另一个问题,Big 的类型如何打印出来? fmt.Printf(“%T\n", Big) 无法打印,提示 ”constant 1267650600228229401496703205376 overflows int“