why use << iota?
tags: learning go programming
content
- in go-iota-with-bit-shift-operator, im seeing something like:
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
ORoperation, or|in Go’s syntax, to combine flags!
myFlags := FlagA | FlagB-
binary wise,
myFlagbecomes0011 -
decimal wise,
myFlagbecome3(but of course, we don’t use decimal in this case, it’s not particularly useful) -
to check if
myFlagscontainsFlagA:- we need to check if
myFlags AND FlagAis all0000
- we need to check if
myFlags 0011
FlagA 0001
--------------
AND 0001- translate to Go’s syntax:
if myFlags & FlagA == FlagA: