Go Wiki: Iota

總結

Go 的 iota 識別符號用於 const 宣告,以簡化遞增數字的定義。由於它可用於表示式,因此提供了超越簡單列舉的通用性。

每當原始碼中出現保留字 const 時(即每個 const 塊),iota 的值就會重置為 0,並且在每個 ConstSpec (例如,每一行)之後增加一。這可以與常量簡寫(省略常量名後的所有內容)結合使用,以非常簡潔地定義相關常量。

Iota:https://golang.com.tw/ref/spec#Iota

常量宣告:https://golang.com.tw/ref/spec#Constant_declarations

示例

官方規範中有兩個很好的例子

https://golang.com.tw/ref/spec#Iota

這是 Effective Go 中的一個例子

type ByteSize float64

const (
    _           = iota // ignore first value by assigning to blank identifier
    KB ByteSize = 1 << (10 * iota)
    MB
    GB
    TB
    PB
    EB
    ZB
    YB
)

星期列舉示例 - iota 的計算方式 - 來自 Learn Go Programming Blog

How iota works

Articles


此內容是 Go Wiki 的一部分。