Go基础:iota关键字的使用
Go基础:iota关键字的使用
iota介绍
iota是go语言的常量计数器,只能在常量的表达式中使用。
其值从0开始,在const中每新增一行将使得iota计数一次,即iota自己增长1(从这点来看,iota可以看成const块中的行索引,记录行数),其值一直自增1直到遇到下一个const关键字,其值才被重新置为0.
在常量声明中,如果一个常量没有赋值,则他就跟上一行的赋值相同。
使用iota能简化定义,在定义枚举时很有用。
iota的使用
iota只能在常量的表达式中使用
// 编译错误: undefined: iota
fmt.Println(iota)
每次 const 出现时,都会让 iota 初始化为0
const a = iota // a=0
const (
b = iota //b=0
c //c=1
)
自定义类型
type Stereotype int
const (
TypicalNoob Stereotype = iota // 0
TypicalHipster // 1
TypicalUnixWizard // 2
TypicalStartupFounder // 3
)
可跳过的值
type AudioOutput int
const (
OutMute AudioOutput = iota // 0
OutMono // 1
OutStereo // 2
_
_
OutSurround // 5
)
位掩码表达式
type Allergen int
const (
IgEggs Allergen = 1 << iota // 1 << 0 which is 00000001 = 1
IgChocolate // 1 << 1 which is 00000010 = 2
IgNuts // 1 << 2 which is 00000100 = 4
IgStrawberries // 1 << 3 which is 00001000 = 8
IgShellfish // 1 << 4 which is 00010000 = 16
)
定义数量级
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)
)
定义在一行的情况,iota 在下一行增长,而不是立即取得它的引用
const (
Apple, Banana = iota + 1, iota + 2 // Apple = 1, Banana = 2
Cherimoya, Durian // Cherimoya = 2, Durian = 3
Elderberry, Fig // Elderberry = 3, Fig = 4
)
中间插队
const (
i = iota // 0
j = 3.14 // 3.14
k = iota // 2
l // 3
)
本文来自博客园,作者:golandhome,转载请注明原文链接:https://www.cnblogs.com/golandhome/p/17286206.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具