Golang常量在编译期被创建。因为在编译期必须确定其值,因此在声明常量时有一些限制。
- 其类型必须是:数值、字符串、布尔值
- 表达式必须是在编译期可计算的
- 声明常量的同时必须进行初始化,其值不可再次修改
定义
const关键字用于声明常量 const [(] 名称 [数据类型] = 表达式 [)] const ( 多个常量名称 [数据类型]= 对应的多个表达式 )
如果定义多行常量而表达式一致时可省略其他行的表达式 声明时如果不指定数据类型,则该常量为无类型常量
const Pi = 3.14159265358 //float64
iota
在Go中使用另一个常量iota计数器,只能在常量的表达式中使用。 iota在const关键字出现时将被重置为0(const内部的第一行之前),const中每新增一行常量声明将使iota计数一次(iota可理解为const语句块中的行索引)。使用iota能简化定义,在定义枚举时很有用。
每次 const 出现时,都会让 iota 初始化为0.
const a = iota // a=0
const (
b = iota //b=0
c //c=1 相当于c=iota
)
可跳过值
const (
a = iota
b
c
_
_
d
)
a、b、c、d分别是0、1、2、5
位掩码表达式
const (
mutexLocked = 1 << iota // mutex is locked
mutexWoken
mutexStarving
mutexWaiterShift = iota
starvationThresholdNs = 1e6
)
上面的结果是: mutexLocked = 1 << 0 mutexWoken = 1 << 1 mutexStarving = 1 <<2 mutexWaiterShift = iota = 3
定义数量级
type ByteSize float64
const (
_ = iota // ignore first value by assigning to blank identifier
KB ByteSize = 1 << (10 * iota) // 1 << (10*1)
MB // 1 << (10*2)
GB // 1 << (10*3)
TB // 1 << (10*4)
PB // 1 << (10*5)
EB // 1 << (10*6)
ZB // 1 << (10*7)
YB // 1 << (10*8)
)