Iota, continued

July 17, 2023

No live stream today. My office/recording studio is being painted. I’ll be back next week with more linter building!


One last detail on iota

Iota

By definition, multiple uses of iota in the same ConstSpec all have the same value:

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](https://go.dev/ref/spec#Constant_declarations) of the last non-empty expression list.

In other words, if you include multiple constant indentifiers within a single ConstantSpec (that is, on a single line), iota has the same value for the entire line.

	const (
		a = iota
		b
		c, d = iota, iota
		e, f
	)
	fmt.Println(a, b, c, d, e, f)

Prints: 0 1 2 2 3 3

I’ve never used this capability. And in fact, until reading this portion of the spec today, I didn’t know it was possible. I’d suggest it’s a feature not likely to be used by many people. In fact, iota itself is such a feature. It’s rare that I use it, and would encourage most people to explicitly declare all constants, rather than relying on it, in the majority of cases.

Quotes from The Go Programming Language Specification Version of December 15, 2022

Share this