实现说明
无类型常量的任意精度可以归结为函数 main。
使用要点
- 每一步打印都带着自己的标签:
int16 sees:、int64 sees:、byte from typed constant:。
常见问题
运行「无类型常量的任意精度」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 int16 sees:、int64 sees:、byte from typed constant: 标签标明各步骤。
核心语句
var b byte = byte(typedInt / (1 << 13)) // 2^20 / 2^13 = 2^7 = 128
代码示例
package main
import "fmt"
// untyped constant: no type yet, arbitrary precision at compile time
const huge = 1 << 40
// typed constant: carries int and must fit it
const typedInt int = 1 << 20
func main() {
// an untyped constant assigns into any type that can hold its value
var n16 int16 = huge / (1 << 30) // 2^40 / 2^30 = 2^10 = 1024
fmt.Println("int16 sees:", n16)
var n64 int64 = huge
fmt.Println("int64 sees:", n64)
// a typed constant needs an explicit conversion for smaller types
var b byte = byte(typedInt / (1 << 13)) // 2^20 / 2^13 = 2^7 = 128
fmt.Println("byte from typed constant:", b)
// untyped arithmetic stays exact before the final assignment
fmt.Println("exact constant sum:", int64(huge+huge))
}