0 day streak
go / intermediate
Snippet

Creating Bitmask Flags with Const and Iota

Using iota in a const block allows you to construct bitwise flags efficiently. Since iota increments by 1 with each line, combining it with the bitwise shift operator (1 << iota) creates unique power-of-two values. These values can then be combined using OR (|) and verified using AND (&).

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main
import "fmt"
type Permission int
const (
Read Permission = 1 << iota
Write
Execute
)
func main() {
userPerm := Read | Write
hasWrite := (userPerm & Write) != 0
hasExecute := (userPerm & Execute) != 0
fmt.Printf("Has write: %t\n", hasWrite)
fmt.Printf("Has execute: %t\n", hasExecute)
}
Breakdown
1
Read Permission = 1 << iota
Initializes the iota sequence at index 0, shifting 1 left by 0 bits, yielding 1.
2
Write
Implicitly replicates the '1 << iota' expression. iota becomes 1, shifting 1 left by 1 bit, yielding 2.
3
userPerm := Read | Write
Combines Read and Write flags using the bitwise OR operator.
4
hasWrite := (userPerm & Write) != 0
Checks for the presence of the Write flag using the bitwise AND operator.