一文搞懂Golang中iota的用法和原理
前言
我們知道iota
是go語言的常量計數(shù)器,只能在常量的const
表達式中使用,在const
關鍵字出現(xiàn)的時將被重置為0
,const
中每新增一行常量聲明iota值自增1(iota
可以理解為const語句塊中的行索引),使用iota可以簡化常量的定義,但其規(guī)則必須要牢牢掌握,否則在我們開發(fā)中可能會造成誤解,本文嘗試全面總結(jié)其使用用法以及其實現(xiàn)原理,需要的朋友可以參考以下內(nèi)容,希望對大家有幫助。
iota的使用
iota在const關鍵字出現(xiàn)時將被重置為0
iota
只能在常量的表達式中使用,iota
在const
關鍵字出現(xiàn)時將被重置為0
。不同const
定義塊互不干擾。
//const關鍵字出現(xiàn)時將被重置為0 const ( a = iota //0 b //1 ) //不同const定義塊互不干擾 const ( c = iota //0 )
按行計數(shù)
const每新增一行常量聲明,iota計數(shù)一次,可以當做const語句中的索引,常用于定義枚舉數(shù)據(jù)。
const ( n1 = iota //0 n2 //1 n3 //2 n4 //3 )
所有注釋行和空行全部忽略
所有注釋行和空行在編譯時期首先會被清除,所以空行不計數(shù)。
const ( a = iota //0 b //1 //此行是注釋 c //2 )
跳值占位
如果某個值不需要,可以使用占位 “_”
,它不是空行,會進行計數(shù),起到跳值作用。
const ( a = iota //0 _ b //2 )
多個iota
同一const塊出現(xiàn)多個iota,只會按照行數(shù)計數(shù),不會重新計數(shù)。
const ( a = iota // a=0 b = iota // b=1 c = iota // c=2 )
一行多個iota
一行多個iota,分別計數(shù)。
const ( a, b = iota, iota // a=0,b=0 c, d // c=1,d=1 )
首行插隊
開頭插隊會進行計數(shù)。
const ( a = 100 // a=100 b = iota // b=1 c = iota // c=2 d // d=3 )
中間插隊
中間插隊會進行計數(shù)。
const ( a = iota // a=0 b = 100 // b=100 c = iota // c=2 d // d=3 )
沒有表達式的常量定義復用上一行的表達式
const ( a = iota // iota = 0 b = 1 + iota // iota = 1 c // iota = 2 )
實現(xiàn)原理
iota定義
iota 源碼在 Go 語言代碼庫中的定義位于內(nèi)建文件 go/src/builtin/builtin.go
中:
const iota = 0 // Untyped int.iota
在這里聲明了一個常量標識符,它的值是0;iota只是一個簡單的整數(shù)0,為什么能作為常量計數(shù)器進行自增的,我們再看一下const的實現(xiàn)。
const
const 塊中每一行在 Go 中使用 spec 數(shù)據(jù)結(jié)構描述, spec 聲明如下:
ValueSpec struct { Doc *CommentGroup // associated documentation; or nil Names []*Ident // value names (len(Names) > 0) Type Expr // value type; or nil Values []Expr // initial values; or nil Comment *CommentGroup // line comments; or nil }
在這個結(jié)構體中有一個切片 ValueSpec.Names,此切片中保存了一行中定義的常量,如果一行定義N個常量,那么 ValueSpec.Names 切片長度即為N。
const塊實際上是spec類型的切片,用于表示const中的多行。
編譯期間構造常量時的偽算法如下:
for iota, spec := range ValueSpecs { for i, name := range spec.Names { obj := NewConst(name, iota...) //此處將iota傳入,用于構造常量 ... } }
iota實際上是遍歷const塊的索引,每行中即便多次使用iota,其值也不會遞增。
到此這篇關于一文搞懂Golang中iota的用法和原理的文章就介紹到這了,更多相關Golang iota內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
一文帶你了解Golang中interface的設計與實現(xiàn)
本文就來詳細說說為什么說?接口本質(zhì)是一種自定義類型,以及這種自定義類型是如何構建起?go?的?interface?系統(tǒng)的,感興趣的小伙伴可以跟隨小編一起學習一下2023-01-01golang 實現(xiàn)Location跳轉(zhuǎn)方式
這篇文章主要介紹了golang 實現(xiàn)Location跳轉(zhuǎn)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05