Goの公式docに沿って「iotaとは何か」を読み取っていきます
iotaの概要
Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants. Its value is the index of the respective ConstSpec in that constant declaration, starting at zero.
(定数宣言内で、事前に宣言された識別子iotaは、型付けされていない連続した整数定数を表す。その値は、定数宣言内の各 ConstSpec のインデックスで、0 から始まります。)
- つまりiotaは定数の宣言行に対応したインデックス
- 補足
- 「型付けされていない整数定数」
- →Intではあるものの、どのIntか(Int8、Int16など)は決まっていないということ
- 「ConstSpec」
- →定数の宣言行のこと
- 「型付けされていない整数定数」
ConstSpecの例)
const (
c0 = iota // ConstSpec1つ目
c1 = iota // ConstSpec2つ目
)
iotaの具体例
例①
// 0からインデックスが割り当てられる
const (
c0 = iota // c0 == 0
c1 = iota // c1 == 1
c2 = iota // c2 == 2
)
例②
// ビット演算については後述
const (
a = 1 << iota // a == 1 (iota == 0) 1を0ビット左へ
b = 1 << iota // b == 2 (iota == 1) 1を1ビット左へ
c = 3 // c == 3 (iota == 2, unused)
d = 1 << iota // d == 8 (iota == 3) 1を3ビット左へ
)
ビット演算
- 「x << y」と書くと「xをyビット左へズラす」という意味
例)
- 1 << 1
- 1を1ビット左へズラす(0001 -> 0010)ので、2になる
- 1 << 3
- 1を3ビット左へズラす(0001 -> 1000)ので、8になる
例③
// 定数に型宣言をつけることで、iotaの結果に型が付く
const (
u = iota * 42 // u == 0 (untyped integer constant)
v float64 = iota * 42 // v == 42.0 (float64 constant)
w = iota * 42 // w == 84 (untyped integer constant)
)
例④
// iotaは定数宣言行のインデックスなので、1行に2つ宣言しても、2回インクリメントされたりはしない
const (
bit0, mask0 = 1 << iota, 1<<iota - 1 // bit0 == 1, mask0 == 0 (iota == 0)
bit1, mask1 // bit1 == 2, mask1 == 1 (iota == 1)
_, _ // (iota == 2, unused)
bit3, mask3 // bit3 == 8, mask3 == 7 (iota == 3)
)
This last example exploits the implicit repetition of the last non-empty expression list.
(この最後の例は、最後の空でない式リストの暗黙の繰り返しを利用している。)
「暗黙の繰り返し」とは
- 連続する定数宣言に、値・式が書かれていない時、直前の値・式が使用されること