首先itoa 是什么

const 内的 iota是golang语言的常量计数器,只能在常量的表达式中使用,,即const内。

iota在const关键字出现时将被重置为0(const内部的第一行之前),const中每新增一行常量声明将使iota计数一次。

可以参照行号理解,也就是说将iota理解为const语句块中的行索引。

关于其特性举例如下:

通过例子说明其各种特性。

1、每次 const 出现时,都会让 iota 初始化为0.

const a = iota // a=0
const (
b = iota //b=0
c //c=1
)

2、自定义类型

自增长常量经常包含一个自定义枚举类型,允许你依靠编译器完成自增设置。

type Newtype int

const (
T1 Newtype = iota // 0
T2 // 1
T3 // 2
T4 // 3
)

3、可跳过的值

type AudioOutput int

const (
OutMute AudioOutput = iota // 0
OutMono // 1
OutStereo // 2
_
_
OutSurround // 5
)

4、位掩码表达式

type Allergen int

const (
IgEggs Allergen = 1 << iota // 1 << 0 which is 00000001
IgChocolate // 1 << 1 which is 00000010
IgNuts // 1 << 2 which is 00000100
IgStrawberries // 1 << 3 which is 00001000
IgShellfish // 1 << 4 which is 00010000
)

5、定义数量级

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)
)

6、定义在一行的情况

跟普通形式 没什么不同

const (
Apple, Banana = iota + 1, iota + 2
Cherimoya, Durian
Elderberry, Fig
)

iota 在下一行增长,而不是立即取得它的引用。

// Apple: 1
// Banana: 2
// Cherimoya: 2
// Durian: 3
// Elderberry: 3
// Fig: 4

7、中间插队

中间插队时,iota 会被覆盖掉 不再继续自增。但是用另一个 iota 接一下,又会继续自增。 示例如下,中间插入了5 和 6, 5下面有itoa 接,6没有。

const(
a = iota
b = 5
c = iota
d = 6
e
f
)

那么打印出来的结果是 0 5 2 6 6 6

好处和坏处

使用iota能简化定义,在定义枚举时很有用。当代码需要改动的时候,也比较易于拓展或者修改。另外看起来也是有些逼格在里边的。

但是itoa 令代码相对的不那么的明了易懂。会加大理解代码的负担。如果刚好遇上一个同事不太懂itoa 的用法,又不愿意学习会加大挖坑的可能性。

所以我建议适当的用,即只用其简单的特性就好了。 我的主张:代码的基本需求之一是 给人看的。机器跑起来没问题,让人能易于看懂才是好代码。

最后,记得有个类似的strconv-itoa

多数语言都会有个 itoa 函数,这个函数跟const 里的itoa大有不同。 itoa函数是用来将数字串转换为字符串的。golang 里的itoa函数是 strconv.Itoa(int)string .

区分清楚这两个,更有助于理解和记忆。

欢迎批评和指正