這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
iota是golang語言的常量計數器,只能在常量的運算式中使用。
iota在const關鍵字出現時將被重設為0(const內部的第一行之前),const中每新增一行常量聲明將使iota計數一次(iota可理解為const語句塊中的行索引)。
使用iota能簡化定義,在定義枚舉時很有用。
舉例如下:
1、iota只能在常量的運算式中使用。
fmt.Println(iota)
編譯錯誤: undefined: iota
2、每次 const 出現時,都會讓 iota 初始化為0.
const a = iota // a=0
const (
b = iota //b=0
c //c=1
)
3、自訂類型
自增長常量經常包含一個自訂枚舉類型,允許你依靠編譯器完成自增設定。
type Stereotype int
const (
TypicalNoob Stereotype = iota // 0
TypicalHipster // 1
TypicalUnixWizard // 2
TypicalStartupFounder // 3
)
4、可跳過的值
設想你在處理消費者的音訊輸出。音頻可能無論什麼都沒有任何輸出,或者它可能是單聲道,立體聲,或是環繞立體聲的。
這可能有些潛在的邏輯定義沒有任何輸出為 0,單聲道為 1,立體聲為 2,值是由通道的數量提供。
所以你給 Dolby 5.1 環繞立體聲什麼值。
一方面,它有6個通道輸出,但是另一方面,僅僅 5 個通道是全頻寬通道(因此 5.1 稱號 - 其中 .1 表示的是低頻效果通道)。
不管怎樣,我們不想簡單的增加到 3。
我們可以使用底線跳過不想要的值。
type AudioOutput int
const (
OutMute AudioOutput = iota // 0
OutMono // 1
OutStereo // 2
_
_
OutSurround // 5
)
5、位元遮罩運算式
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
)
這個工作是因為當你在一個 const 組中僅僅有一個標示符在一行的時候,它將使用增長的 iota 取得前面的運算式並且再運用它,。在 Go 語言的 spec 中, 這就是所謂的隱性重複最後一個非空的運算式列表。
如果你對雞蛋,巧克力和海鮮過敏,把這些 bits 翻轉到 “on” 的位置(從左至右映射 bits)。然後你將得到一個 bit 值 00010011,它對應十進位的 19。
fmt.Println(IgEggs | IgChocolate | IgShellfish)
// output:
// 19
6、定義數量級
type ByteSize float64const ( _ = 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 在下一行增長,而不是立即取得它的引用。
// Apple: 1
// Banana: 2
// Cherimoya: 2
// Durian: 3
// Elderberry: 3
// Fig: 4
8、中間插隊
const (
i = iota
j = 3.14
k = iota
l
)
那麼列印出來的結果是 i=0,j=3.14,k=2,l=3
參考資料:
iota: Golang 中優雅的常量
http://segmentfault.com/blog/yexiaobai/1190000000656284
老虞學GoLang筆記-常量
http://www.cnblogs.com/howDo/archive/2013/04/15/golang-constant.html
初識golang,變數,常量,iota的學習
http://my.oschina.net/u/698121/blog/156235