Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

定数の設定で楽をするiota記法

iota記法を使うと定数の設定で楽をできます。

実際のところ

The Go Programming Language Specification - The Go Programming Language
公式によると、こんな動きをします。

const ( // iota is reset to 0
	c0 = iota  // c0 == 0
	c1 = iota  // c1 == 1
	c2 = iota  // c2 == 2
)

const ( // iota is reset to 0
	a = 1 << iota  // a == 1
	b = 1 << iota  // b == 2
	c = 3          // c == 3  (iota is not used but still incremented)
	d = 1 << iota  // d == 8
)

一定パターンが続くなら、冒頭に書いておけば後は連番を勝手に入れてくれます。
具体的な例として、go-humanizeではこんな使われ方をしています。

// bytes.go:13-
const (
	Byte = 1 << (iota * 10)
	KiByte
	MiByte
	GiByte
	TiByte
	PiByte
	EiByte
)