Go 语言常量
const、iota、无类型常量,以及编译期能算什么。
Key Points`iota` 在 `const` 块里从 0 开始自增,每换一行加 1,是 Go 的枚举写法。
基本用法
Go
const Pi = 3.14159
const Name string = "go"
const (
A = 1
B = 2
C = 3
)A constant's value must be known at compile time. So const t = time.Now() is invalid while const n = 2 * 3 is fine.
iota
Go
type Weekday int
const (
Sunday Weekday = iota // 0
Monday // 1
Tuesday // 2
Wednesday // 3
)
fmt.Println(Sunday, Monday, Tuesday, Wednesday)Output
0 1 2 3Go
// 位标志
const (
ReadPerm = 1 << iota // 1
WritePerm // 2
ExecPerm // 4
)
fmt.Println(ReadPerm|WritePerm, ExecPerm)Output
3 4Go
// 跳过某些值
const (
_ = iota // 丢弃 0
KB = 1 << (10 * iota) // 1024
MB // 1048576
GB // 1073741824
)
fmt.Println(KB, MB, GB)Output
1024 1048576 1073741824无类型常量
Go
const Big = 1 << 62
var f float64 = Big // 常量可无损转换
fmt.Println(f)
// 但常量运算溢出会在编译期报错
// const Over = 1 << 64Untyped constants are a neat Go design: const x = 1 has no concrete type and can be assigned to int, float64 or byte as long as it fits. Constants stay precise without conversions everywhere.
常量 vs 变量
| Aspect | const | var |
|---|---|---|
| 何时确定 | 编译期 | 运行时 |
| 能否取地址 | 不能 | 能 |
| 能否用 iota | 能 | 不能 |
| 类型 | 可以无类型 | 必须有类型 |
Go's
const is not a read-only variable; it is a compile-time substitution. There are no const arrays or structs — only basic types and strings.基本用法
Go
const Pi = 3.14159
const Name string = "go"
const (
A = 1
B = 2
C = 3
)常量的值必须在编译期确定。所以 const t = time.Now() 是错的,而 const n = 2 * 3 是对的。
iota
Go
type Weekday int
const (
Sunday Weekday = iota // 0
Monday // 1
Tuesday // 2
Wednesday // 3
)
fmt.Println(Sunday, Monday, Tuesday, Wednesday)Output
0 1 2 3Go
// 位标志
const (
ReadPerm = 1 << iota // 1
WritePerm // 2
ExecPerm // 4
)
fmt.Println(ReadPerm|WritePerm, ExecPerm)Output
3 4Go
// 跳过某些值
const (
_ = iota // 丢弃 0
KB = 1 << (10 * iota) // 1024
MB // 1048576
GB // 1073741824
)
fmt.Println(KB, MB, GB)Output
1024 1048576 1073741824无类型常量
Go
const Big = 1 << 62
var f float64 = Big // 常量可无损转换
fmt.Println(f)
// 但常量运算溢出会在编译期报错
// const Over = 1 << 64无类型常量是 Go 的一个精巧设计:const x = 1 的 x 没有具体类型,赋值给 int、float64、byte 都能直接用,只要不溢出。这让常量既有精度又不必到处转换。
常量 vs 变量
| 对比项 | const | var |
|---|---|---|
| 何时确定 | 编译期 | 运行时 |
| 能否取地址 | 不能 | 能 |
| 能否用 iota | 能 | 不能 |
| 类型 | 可以无类型 | 必须有类型 |
Go 的
const 不是「只读变量」,它是编译期替换。所以 const 数组、const 结构体都不存在——只有基本类型和字符串能当常量。