关键字 iota 用来声明枚举 ,默认开始值为 0 ,const 中每增加一行加 1 。
package main
import "fmt"
const (
a = iota // a = 0
_ // 略过 iota 为 1 的情况
b // 常量声明省略值时默认使用 iota 自增 b = 2
c = "C" // 虽然此行未使用 iota 但此行 iota 依然自增
d // 继承 c 的值 d = "C"
e, f = iota, iota // iota 在同一行值相同 e = 5, f = 5
g = iota // 此行必须重新指定 iota 以自增,否则编译不通过 g = 6
h // h = 7
)
const (
u = "hello"
v = iota // iota 每遇到一个 const 关键字就会重置为 0, const 中每新增一行常量声明将使 iota 计数一次 v = 1
)
const (
// iota 参与运算
B = 1 << (10 * iota) // 1 << 0
KB // 1 << 10 = 1024
MB // 1 << 20 = 1024 * 1024
GB // 1 << 30 = 1024 * 1024 * 1024
TB
PB
)
type Level int
const (
Best Level = iota
Nice
Normal
Bad
)
// 使用 fmt.Printf()、fmt.Print() 和 fmt.Println() 会自动使用 String() 方法
func (l Level) String() string {
return [...]string{"Best", "Nice", "Normal", "Bad"}[l]
}
func main() {
fmt.Println(a, b, c, d, e, f, g, h, v)
fmt.Println(B, KB, MB, GB, TB, PB, 1<<20)
fmt.Println(Normal)
}
/*
0 2 C C 5 5 6 7 1
1 1024 1048576 1073741824 1099511627776 1125899906842624 1048576
Normal
*/ 本文标题:golang iota 笔记
版权声明:本文使用「署名-非商业性使用-相同方式共享」创作共享协议,转载或使用请遵守署名协议。
相关文章
上一篇:红色之旅——井冈山