Runtime enums

  1. Immutable: New
  2. Parsing
  3. Defaults
  4. Mutable: NewMutable
  5. Which should I use?

When you don’t want a generation step, build the enum at runtime. Def and MutableDef work with any comparable type — strings, ints, or your own named types.

Immutable: New

status := enumx.New("pending", "active", "blocked")

status.Has("active")   // true
status.Values()        // [pending active blocked] — insertion order, defensive copy

Parsing

Parse returns an EnumValue[T], a wrapper that proves the value was validated:

val, err := status.Parse("active")

val.Is("active")  // true
val.Valid()       // true
val.Unwrap()      // "active"
val.String()      // "active"

Parse takes a T. For raw input — a query parameter, an env var — use ParseString, which takes a plain string and does the conversion for you:

val, err := enumx.ParseString(status, r.FormValue("status"))

ParseStringMutable is the same thing for a MutableDef. Both return ErrEmptyEnum for an empty string.

Defaults

status.Default("pending")
status.IsDefault("pending") // true

Default panics if the value is not a member, on both Def and MutableDef. A typo fails at init rather than silently setting a default that nothing matches.

Mutable: NewMutable

MutableDef is safe for concurrent use — every method takes the lock.

codes := enumx.NewMutable[int]()
codes.Add(200).Add(404).Add(500)
codes.Remove(404)
codes.Values() // [200 500]

Add ignores a value that is already present, and Remove ignores one that is absent, so both are idempotent and chainable.

Which should I use?

  Def / New MutableDef / NewMutable
Membership fixed at construction ✅ —
Values added or removed later — ✅
Lock taken on every read no yes
Safe for concurrent writes no ✅

Prefer Def unless the value set genuinely changes at runtime. Its methods take no lock, and an enum that cannot change is easier to reason about.

Def is immutable in its membership. Default, AddTranslation, and SetTranslation do mutate it, so call them during initialization, before the value is shared across goroutines.