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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.