State machine & metadata
State machine
Most string enums are really states, and most bugs around them are illegal jumps. Declare the legal edges once and check them anywhere.
enumx.RegisterTransitions(
enumx.Transition[Status]{From: StatusPending, To: StatusActive},
enumx.Transition[Status]{From: StatusActive, To: StatusBlocked},
)
// Or one at a time
enumx.AddTransition(StatusPending, StatusBlocked)
enumx.CanTransition(StatusPending, StatusActive) // true
enumx.CanTransition(StatusBlocked, StatusActive) // false
enumx.NextStates(StatusPending) // [active blocked]
enumx.NextStates(StatusBlocked) // nil — terminal
NextStates returns states in registration order, and is deterministic. Registration is additive and safe to call from several goroutines.
Prefer declaring transitions in the definition file with
enumx.Transitions— see Code generation. The generator validates every state name at build time and addsCanTransitionTo,NextStates, andTomethods directly to your type.
Per-value metadata
Attach arbitrary typed data to a value and read it back type-safely. The metadata type is part of the lookup key, so one value can carry several unrelated pieces of data.
type Policy struct{ RetryAfter time.Duration }
type Display struct{ Colour string }
enumx.RegisterMeta(StatusBlocked, Policy{RetryAfter: time.Hour})
enumx.RegisterMeta(StatusBlocked, Display{Colour: "red"})
p, ok := enumx.Meta[Status, Policy](StatusBlocked) // typed, no assertion
d, ok := enumx.Meta[Status, Display](StatusBlocked)
Meta returns the zero value and false when nothing is registered.
Exhaustive matching
Go’s switch will not tell you when you add an enum value and forget a branch. Match will — it panics if any registered value is unhandled, so the gap surfaces in your tests rather than in production.
label := enumx.Match(status, enumx.Cases[Status, string]{
StatusPending: func() string { return "waiting" },
StatusActive: func() string { return "live" },
StatusBlocked: func() string { return "stopped" },
})
It also panics if the value being matched is itself invalid.
MatchBuilder returns a *Matcher[T, R]. The builder form is equivalent, and reads better when the handlers are long:
label := enumx.MatchBuilder[Status, string](status).
Case(StatusPending, func() string { return "waiting" }).
Case(StatusActive, func() string { return "live" }).
Case(StatusBlocked, func() string { return "stopped" }).
Must()
Matchchecks exhaustiveness at runtime, not compile time. Cover each enum in a test so a missing case fails your suite. For plainswitchstatements,enumx lintcatches the same gap in CI.