iota是golang語言的常量計(jì)數(shù)器,只能在常量的表達(dá)式中使用东跪。
iota在const關(guān)鍵字出現(xiàn)時(shí)將被重置為0(const內(nèi)部的第一行之前)董济,const中每新增一行常量聲明將使iota計(jì)數(shù)一次(iota可理解為const語句塊中的行索引)。
使用iota能簡化定義,在定義枚舉時(shí)很有用。
舉例如下:##
1指黎、iota只能在常量的表達(dá)式中使用。
fmt.Println(iota)
//編譯錯誤: undefined: iota
2州丹、每次 const 出現(xiàn)時(shí)醋安,都會讓 iota 初始化為0.
const a = iota // a=0
const (
b = iota //b=0
c //c=1 相當(dāng)于c=iota
)
3、自定義類型
自增長常量經(jīng)常包含一個自定義枚舉類型墓毒,允許你依靠編譯器完成自增設(shè)置茬故。
type Stereotype int
const (
TypicalNoob Stereotype = iota // 0
TypicalHipster // 1 TypicalHipster = iota
TypicalUnixWizard // 2 TypicalUnixWizard = iota
TypicalStartupFounder // 3 TypicalStartupFounder = iota
)
4、可跳過的值
設(shè)想你在處理消費(fèi)者的音頻輸出蚁鳖。
音頻可能無論什么都沒有任何輸出,或者它可能是單聲道赁炎,立體聲醉箕,或是環(huán)繞立體聲的。
這可能有些潛在的邏輯定義沒有任何輸出為 0徙垫,單聲道為 1讥裤,立體聲為 2,值是由通道的數(shù)量提供姻报。
所以你給 Dolby 5.1 環(huán)繞立體聲什么值己英。
一方面,它有6個通道輸出吴旋,但是另一方面损肛,僅僅 5 個通道是全帶寬通道(因此 5.1 稱號 - 其中 .1 表示的是低頻效果通道)。
不管怎樣荣瑟,我們不想簡單的增加到 3治拿。
我們可以使用下劃線跳過不想要的值。
//如果兩個const的賦值語句的表達(dá)式是一樣的笆焰,那么可以省略后一個賦值表達(dá)式劫谅。
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
)
6、定義數(shù)量級
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 // = iota + 1, iota + 2
Elderberry, Fig //= iota + 1, iota + 2
)
iota 在下一行增長荞驴,而不是立即取得它的引用。
// 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
下面是一個常規(guī)的枚舉表示法熊楼,其中定義了一系列整型常量:
const (
Sunday = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
numberOfDays // 這個常量沒有導(dǎo)出
)
參考資料:
iota: Golang 中優(yōu)雅的常量
http://segmentfault.com/blog/yexiaobai/1190000000656284
老虞學(xué)GoLang筆記-常量
http://www.cnblogs.com/howDo/archive/2013/04/15/golang-constant.html
初識golang,變量冤狡,常量孙蒙,iota的學(xué)習(xí)
http://my.oschina.net/u/698121/blog/156235