当前位置:网站首页>Golang中iota的正确用法
Golang中iota的正确用法
2022-07-22 23:02:00 【百家饭隐私计算】
Golang中有一个iota
iota是Go语言的预声明标识符,用于常量的声明。
iota的值是const语句块里的行索引,值从0开始,每次递增加1。通过下面的代码示例我们先回顾下iota的特性。
我原来用iota主要这么用:
const (
ErrType1 = 10000 + iota
ErrType2 = 10000 + iota
ErrType3 = 10000 + iota
)感觉是不是有点脱了啥放P?
后来我了解到Golang的常量定义,如果一行没有 = 以及后面这一串,是复用上一行的,
比如上面的可以改成这样:
const (
ErrType1 = 10000 + iota
ErrType2
ErrType3
)你猜ErrType2和ErrType3是多少值?没错,是10001和10002,这一段综合使用了golang的iota作为const行号和const无需重复定义模式的两个特性,完成了一组很简单方便的常量定义。
有没有恍然大悟的感觉,这样才起到了简化的作用嘛。
同样的方式,其他运算符也是同样可以这样用的,比如这样:
const (
ErrType1 = 1 << iota
ErrType2
ErrType3
)那ErrType2和ErrType3就变成了2和4,很方便就能做按位设值了。
边栏推荐
- 数的三次方根
- What level of futures company is founder metaphase? Is the account opening safe and reliable?
- 将childNodes返回的伪数组转化为真数组
- flink使MapState实现KeyedState
- The author believes that the development logic of the meta universe and the Internet is quite different in Chengdu
- 构造函数的初始化、清理及const修饰成员函数
- Redis 事务学习有感
- Several ways of QT thread exit
- How to realize synchronized
- Come on, slide to the next little sister
猜你喜欢

"Weilai Cup" 2022 Niuke summer multi school training camp 1

三种缓存策略:Cache Aside 策略、Read/Write Through 策略、Write Back 策略

类和对象上案例

EMQX v4.4.5 发布:新增排他订阅及 MQTT 5.0 发布属性支持

Understand the interrupt system in STM32 in simple terms -- from principle to simple engineering examples -- nanny level tutorial

Redis 持久化操作 (RDB, AOF)

93.(leaflet篇)leaflet态势标绘-进攻方向修改

Algorithm --- 2D array mesh migration (kotlin)

Go 并发编程基础:什么是上下文

Redis 配置文件
随机推荐
y74.第四章 Prometheus大厂监控体系及实战 -- PromQL简介和监控pod资源(五)
Several ways of QT thread exit
[reading notes > statistics] 12-01 construction of confidence interval - Introduction to the concept of confidence interval
"Weilai Cup" 2022 Niuke summer multi school training camp 1
Get a control width
What if Alibaba cloud international forgets its member name or login password?
Come on, slide to the next little sister
Xmodem、Ymodem和Zmodem协议是最常用的三种通信协议
Can the formatted data of the USB flash disk be recovered? How to recover the formatted data of the USB flash disk
Algorithm --- use the minimum cost to climb stairs (kotlin)
MSG | 开源与结缘,昇思携梦前行!
SSH 免密登陆配置
气不过“自愿降薪”,裸辞面字节,四天三面,结局居然这样?
js 正则删除span标签以及标签里面的内容
Redistemplate pipeline use
挖财和启牛都是干什么的开户安全吗?
The cubic root of a number
Typora设置标题自动添加序号
获取一个控件宽度
Redis persistence operation (RDB, AOF)