Go 语言常量

const、iota、无类型常量,以及编译期能算什么。

Beginner
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 3
Go
// 位标志
const (
	ReadPerm = 1 << iota    // 1
	WritePerm               // 2
	ExecPerm                // 4
)

fmt.Println(ReadPerm|WritePerm, ExecPerm)
Output
3 4
Go
// 跳过某些值
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

Untyped 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 变量

Aspectconstvar
何时确定编译期运行时
能否取地址不能能
能否用 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.

Friends & Partners