首先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 .
區分清楚這兩個,更有助於理解和記憶。
歡迎批評和指正