1. Go 常量溯源
Go 中所有与常量有关的声明都通过 const 来进行,例如:
// $GOROOT/src/os/file.goconst (// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.O_RDONLY int = syscall.O_RDONLY // open the file read-only.O_WRONLY int = syscall.O_WRONLY // open the file write-only.O_RDWR int = syscall.O_RDWR // open the file read-write.// The remaining values may be or'ed in to control behavior.O_APPEND int = syscall.O_APPEND // append data to the file when writing.O_CREATE int = syscall.O_CREAT // create a new file if none exists.O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist.O_SYNC int = syscall.O_SYNC // open for synchronous I/O.O_TRUNC int = syscall.O_TRUNC // truncate regular writable file when opened.)
绝大多数情况下,Go 常量在声明时并不显式指定类型,也就是说使用的是无类型常量(untyped constants)。比如:
// $GOROOT/src/io/io.go// Seek whence values.const (SeekStart = 0 // seek relative to the origin of the fileSeekCurrent = 1 // seek relative to the current offsetSeekEnd = 2 // seek relative to the end)
2. 有类型常量带来的“烦恼”
不可以被相互比较或混在一个表达式中进行运算:
type myInt intfunc main() {var a int = 5var b myInt = 6fmt.Println(a + b) // invalid operation: a + b (mismatched types int and myInt)}
必须进行显式地转型:
type myInt intfunc main() {var a int = 5var b myInt = 6fmt.Println(a + int(b)) // 输出:11}
有类型常量与变量混合在一起进行运算求值时也要遵循这一要求:
type myInt intconst n myInt = 13const m int = n + 5 // cannot use n + 5 (type myInt) as type int in const initializerfunc main() {var a int = 5fmt.Println(a + n) // invalid operation: a + n (mismatched types int and myInt)}
唯有通过显式转型才能让上面代码正常工作:
type myInt intconst n myInt = 13const m int = int(n) + 5func main() {var a int = 5fmt.Println(a + int(n)) // 输出:18}
3. 无类型常量消除烦恼,简化代码
const (a = 5pi = 3.1415926s = "Hello, Gopher"c = 'a'b = false)type myInt inttype myFloat float32type myString stringfunc main() {var j myInt = avar f myFloat = pivar str myString = sfmt.Println(j) // 输出:5fmt.Println(f) // 输出:3.1415926fmt.Println(str) // 输出:Hello, Gopher}
无类型常量也拥有自己的默认类型:无类型的布尔型常量、无类型的整数常量、无类型的字符常量、无类型的浮点数常量、无类型的复数常量、无类型的字符串常量分别对应的默认类型为 bool、int、int32(rune)、float64、complex128 和 string。当常量被赋值给无类型变量、接口变量时,常量默认类型对于确定无类型变量的类型以及接口对应动态类型是至关重要的:
const (a = 5s = "Hello, Gopher")func main() {n := avar i interface{} = afmt.Printf("%T\n", n) // 输出:intfmt.Printf("%T\n", i) // 输出:inti = sfmt.Printf("%T\n", i) // 输出:string}
4. 小结
数值型无类型常量还可以提供比基础类型更高精度的算术运算,你可以认为至少有 256bit 的运算精度。
