Iota, a symbol I don't understand

In
const (
a = 1 << iota // a == 1 (iota == 0)
b = 1 << iota // b == 2 (iota == 1)
c = 3 // c == 3 (iota == 2, unused)
d = 1 << iota // d == 8 (iota == 3)
)
what does << signify.

It’s a “bit shift.” Computers store numbers in binary so:

  • 0001 in binary is 1 in decimal
  • 0010 in binary is 2 in decimal
  • 0100 in binary is 4 in decimal
  • 1000 in binary is 8 in decimal

The expression 1 << 1 means “take a binary 1 and shift it to the left one column” which doubles it to 2. 1 << 2 means to shift it over 2 columns so it becomes 4, just like the list above.

iota is a counter in Go. If I wanted to use English names for numbers instead of writing them out, I could do this:

const (
  Zero = iota
  One = iota
  Two = iota
)

Then I could say One + Two in my program to get 3. This would be a little silly to do for real because it’s easier to read and write 1 + 2, but it demonstrates what iota does.

You can combine bit shifting (i.e. <<) and iota like in the sample you posted so that instead of counting by 1, each row doubles to 1, 2, 4, 8, 16, etc.

EDIT: typos

5 Likes

Thank you. I understand now.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.