iota是golang語言的常量計(jì)數(shù)器,只能在常量的表達(dá)式中使用。
iota在const關(guān)鍵字出現(xiàn)時(shí)將被重置為0(const內(nèi)部的第一行之前),const中每新增一行常量聲明將使iota計(jì)數(shù)一次(iota可理解為const語句塊中的行索引)。
使用iota能簡(jiǎn)化定義,在定義枚舉時(shí)很有用。
舉例如下:
1、iota只能在常量的表達(dá)式中使用。
fmt.Println(iota)
編譯錯(cuò)誤: undefined: iota
2、每次 const 出現(xiàn)時(shí),都會(huì)讓 iota 初始化為0.
const a = iota // a=0
const (
b = iota //b=0
c //c=1
)
3、自定義類型
自增長(zhǎng)常量經(jīng)常包含一個(gè)自定義枚舉類型,允許你依靠編譯器完成自增設(shè)置。
type Stereotype int
const (
TypicalNoob Stereotype = iota // 0
TypicalHipster // 1
TypicalUnixWizard // 2
TypicalStartupFounder // 3
)
4、可跳過的值
設(shè)想你在處理消費(fèi)者的音頻輸出。音頻可能無論什么都沒有任何輸出,或者它可能是單聲道,立體聲,或是環(huán)繞立體聲的。
這可能有些潛在的邏輯定義沒有任何輸出為 0,單聲道為 1,立體聲為 2,值是由通道的數(shù)量提供。
所以你給 Dolby 5.1 環(huán)繞立體聲什么值。
一方面,它有6個(gè)通道輸出,但是另一方面,僅僅 5 個(gè)通道是全帶寬通道(因此 5.1 稱號(hào) - 其中 .1 表示的是低頻效果通道)。
不管怎樣,我們不想簡(jiǎn)單的增加到 3。
我們可以使用下劃線跳過不想要的值。
type AudioOutput int
const (
OutMute AudioOutput = iota // 0
OutMono // 1
OutStereo // 2
_
_
OutSurround // 5
)
5、位掩碼表達(dá)式
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
)
這個(gè)工作是因?yàn)楫?dāng)你在一個(gè) const 組中僅僅有一個(gè)標(biāo)示符在一行的時(shí)候,它將使用增長(zhǎng)的 iota 取得前面的表達(dá)式并且再運(yùn)用它,。在 Go 語言的 spec 中, 這就是所謂的隱性重復(fù)最后一個(gè)非空的表達(dá)式列表。
如果你對(duì)雞蛋,巧克力和海鮮過敏,把這些 bits 翻轉(zhuǎn)到 “on” 的位置(從左到右映射 bits)。然后你將得到一個(gè) bit 值 00010011,它對(duì)應(yīng)十進(jìn)制的 19。
fmt.Println(IgEggs | IgChocolate | IgShellfish)
// output:
// 19
6、定義數(shù)量級(jí)
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)
)
7、定義在一行的情況
const (
Apple, Banana = iota + 1, iota + 2
Cherimoya, Durian
Elderberry, Fig
)
iota 在下一行增長(zhǎng),而不是立即取得它的引用。
// Apple: 1
// Banana: 2
// Cherimoya: 2
// Durian: 3
// Elderberry: 3
// Fig: 4
8、中間插隊(duì)
const (
i = iota
j = 3.14
k = iota
l
)
那么打印出來的結(jié)果是 i=0,j=3.14,k=2,l=3
9、二進(jìn)制移動(dòng)
const (
bit00 uint32 = 5 << iota //bit00=5
bit01 //bit01=10
bit02 //bit02=20
)
fmt.Printf("bit00 = %d, bit01 = %d, bit02 = %d\n", bit00, bit01, bit02)
//bit00 = 5, bit01 = 10, bit02 = 20