why use << iota?

tags: learning go programming

content

const (
    FlagA = 1 << iota   // 1  (binary: 0001)
    FlagB               // 2  (binary: 0010)
    FlagC               // 4  (binary: 0100)
    FlagD               // 8  (binary: 1000)
)
  • why do we wanna use these, other than normal iota?

    • one use case is to combine flags!
  • we can now use bit-wise OR operation, or | in Go’s syntax, to combine flags!

myFlags := FlagA | FlagB
  • binary wise, myFlag becomes 0011

  • decimal wise, myFlag become 3 (but of course, we don’t use decimal in this case, it’s not particularly useful)

  • to check if myFlags contains FlagA:

    • we need to check if myFlags AND FlagA is all 0000
myFlags  0011
FlagA    0001
--------------
AND      0001
  • translate to Go’s syntax:
if myFlags & FlagA == FlagA:

up

down

reference