iota是golang語言的常量計數器,只能在常量的表達式中使用。
iota在const關鍵字出現時將被重置為0(const內部的第一行之前),const中每新增一行常量聲明將使iota計數一次(iota可理解為const語句塊中的行索引)。 (推薦學習:go)
使用iota能簡化定義,在定義枚舉時很有用。
在常量定義中,iota可以方便的迭代一個值從0以步長1遞增,0,1,2,3,4,5…
本例以文件大小的格式2的10次方進位一次為依據,將KB為1左移10位,MB左移20位。。。
本文中的Sprintf(“%f”,x)并不會因為定義在String方法內而引起無窮循環bug,因為%f不會去嘗試調用String()
package main import ( "fmt" ) type ByteSize float64 const ( _ = iota KB ByteSize = 1 << (10*iota) MB GB TB PB EB ZB YB ) func (b ByteSize) String() string{ switch { case b >= YB: return fmt.Sprintf("%.2fYB",b/YB) case b >= ZB: return fmt.Sprintf("%.2fZB",b/ZB) case b >= EB: return fmt.Sprintf("%.2fEB",b/EB) case b >= PB: return fmt.Sprintf("%.2fPB",b/PB) case b >= TB: return fmt.Sprintf("%.2fTB",b/TB) case b >= GB: return fmt.Sprintf("%.2fGB",b/GB) case b >= MB: return fmt.Sprintf("%.2fMB",b/MB) case b >= KB: return fmt.Sprintf("%.2fKB",b/KB) } return fmt.Sprintf("%.2fB",b) } func main() { fmt.Println(ByteSize(1e10)) }