常量
//显式类型定义
const a string ="test"
//隐式类型定义
const b = 20
//多个常量定义
const(
c = "test2"
d = 2.3
e = 27
)
iota
iota是Golang语言的常量计数器,只能在常量表达式中使用
iota在const关键字出现时将被重置为0,const中每新增一行常量声明将使iota计数一次
const (
first = iota
second = iota
third = iota
)
const (
first_1 = iota
second_1
third_1
)
const (
first_2 = iota+1
second_2
third_2
)
func main() {
fmt.Println(first, second, third)
fmt.Println(first_1, second_1, third_1)
fmt.Println(first_2, second_2, third_2)
}
输出结果:

注:
iota是const语句块中的行索引,而不是变量索引,其计数只与const语句块中的行数相关
const (
d1 = iota //0
d2 = 20 //20
d3 = iota //2
)
文章介绍了Golang语言中的常量定义,包括显式和隐式类型定义,并重点讲解了iota计数器的工作机制。在const块中,iota在每次声明时递增,用于快速初始化序列化的常量。示例展示了如何在不同const块中使用iota以及如何通过iota+常数来定制计数。
2022

被折叠的 条评论
为什么被折叠?



