Iota Builds Bit Flag Permission Masks

A const block with 1 << iota produces non-overlapping bit flags, and a has method checks permission masks with bitwise AND instead of booleans.

GoConfig Management

Code

gosnippet
42 lines
package main

import "fmt"

// 1 << iota produces non-overlapping bit flags: one bit per capability
type perm uint8

const (
	read    perm = 1 << iota // 1
	write                    // 2
	approve                  // 4
	admin                    // 8
)

// has checks whether a capability bit is set in the mask
func (p perm) has(want perm) bool {
	return p&want == want
}

func (p perm) String() string {
	names := [...]string{"read", "write", "approve", "admin"}
	out := ""
	for i, name := range names {
		if p&(perm(1)<<i) != 0 {
			if out != "" {
				out += "|"
			}
			out += name
		}
	}
	return out
}

func main() {
	editor := read | write
	reviewer := read | approve
	fmt.Println("editor:", editor)
	fmt.Println("reviewer:", reviewer)
	fmt.Println("editor can write:", editor.has(write))
	fmt.Println("editor can approve:", editor.has(approve))
	fmt.Println("admin covers editor:", (read | write | approve | admin).has(editor))
}

How the snippet works

Iota Builds Bit Flag Permission Masks comes down to the functions has, String and main.

Iteration happens inside for i, name := range names — everything outside it runs once.

Applying it

Entry signature: func (p perm) String() string

Look for the editor:, reviewer:, editor can write: prefixes when the file runs; they tie each line to its step.

main sequences has; executing the file runs that flow once.

Statements that matter most here

func (p perm) has(want perm) bool {
return p&want == want
}
for i, name := range names {
if p&(perm(1)<<i) != 0 {
if out != "" {
out += "|"
}
out += name
}
}

Interactive Tools for This Topic

FAQ

What does Iota Builds Bit Flag Permission Masks print when run?
Invoke the file as-is — the `editor:`, `reviewer:`, `editor can write:` prefixes identify which step printed each line.