Sets & flags
Two ways to model “several values at once”. Use Set[T] for string enums; use bitmask flags when you need a compact integer, typically because a database column or a wire format demands one.
Set[T]
allowed := enumx.NewSet(StatusPending, StatusActive)
allowed.Has(StatusActive) // true
allowed.HasAll(StatusPending, StatusActive) // true
allowed.HasAny(StatusBlocked) // false
allowed.Len(), allowed.IsEmpty()
Build one from every registered value with AllOf:
enumx.AllOf[Status]() // {pending, active, blocked}
allowed.Complement() // {blocked}
Algebra
a.Union(b) // in either
a.Intersect(b) // in both
a.Diff(b) // in a, not in b
a.Subset(b) // every value of a is in b
a.Equal(b) // same values, order irrelevant
a.Clone() // independent copy
Every operation returns a new Set; none mutate their operands. Add and Remove do mutate, and return the set for chaining.
Deterministic ordering
Slice() returns values in registration order, not map order, so output is stable across runs:
allowed.Slice() // [pending active]
allowed.String() // "pending,active"
Values in the set that were never registered sort after the registered ones, so the result is deterministic either way.
Parsing and JSON
set, err := enumx.ParseSet[Status]("pending, active", ",")
Surrounding spaces and empty elements are ignored; an unregistered element is an error. An empty separator defaults to ",".
A Set marshals to a JSON array in Slice order and validates every element in both directions. An empty set encodes as [], never null.
Setis a map underneath. The zero value cannot be written to — build one withNewSetorAllOf— and like any map it is not safe for concurrent writes.
Bitmask flags
type Perm uint8
const (
PermRead Perm = 1 << iota
PermWrite
PermExec
)
enumx.RegisterFlags(map[Perm]string{
PermRead: "read", PermWrite: "write", PermExec: "exec",
})
enumx.HasFlag(mask, PermRead)
enumx.SetFlag(&mask, PermWrite)
enumx.ClearFlag(&mask, PermWrite)
enumx.FormatFlags(PermRead | PermWrite) // "read | write"
mask, err := enumx.ParseFlags[Perm]("read | exec")
FormatFlags emits labels in ascending flag-value order, so the output is stable across calls and processes — safe to store, compare, and assert on. Unregistered bits are ignored.
ParseFlags tolerates surrounding spaces and empty segments, and returns ErrInvalidEnum for an unknown label.
FlagSet[T]
The same thing behind an OOP API. Every flag function is constrained by enumx.Integer, so any signed or unsigned integer type works — uint8 here, int64 if a column demands it:
fs := enumx.FlagSet[Perm]{}
fs.Add(PermRead)
fs.Has(PermRead) // true
fs.Remove(PermRead)
fs.String() // formatted labels