這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
Numeric constants are high-precision values.
An untyped constant takes the type needed by its context.
Try printing needInt(Big)
too.
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))}
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(Small); var intVariable int = 1 //var float32Variable float32 = 1.2 fmt.Println(needInt(Small)) // constant 1267650600228229401496703205376 overflows int //fmt.Println(needInt(Big)) fmt.Println(needFloat(Small)) fmt.Println(needFloat(Big)) //go語言對類型的要求是很嚴格的,所以你不能傳遞int到float中或者float到int fmt.Println(needInt(intVariable)) //cannot use float32Variable (type float32) as type int in argument to needInt //fmt.Println(needInt(float32Variable)) //cannot use intVariable (type int) as type float64 in argument to needFloat //fmt.Println(needFloat(intVariable)) //cannot use float32Variable (type float32) as type float64 in argument to needFloat //fmt.Println(needFloat(float32Variable))}
不過常量卻相對寬容一些
//constant 1267650600228229401496703205376 overflows int fmt.Println(Big);