Validation & codecs

  1. Register your type
    1. Comparison helpers
  2. Enum[T]: validation at every boundary
  3. NullEnum[T]: when absent is a real state
  4. Forgiving input

The runtime builders hold their values in a Def. The registry is the other half of enumx: register a named string type once, and every package-level generic works with it — parsing, sets, JSON, SQL, metadata, and aliases.

Register your type

type Status string

const (
    StatusPending Status = "pending"
    StatusActive  Status = "active"
    StatusBlocked Status = "blocked"
)

func init() {
    enumx.Register(StatusPending, StatusActive, StatusBlocked)
}

Code generation emits this init() for you.

enumx.IsValid(StatusActive)          // true
enumx.Values[Status]()               // registration order
enumx.Parse[Status]("active")        // (active, nil)
enumx.IsAny(s, StatusActive, StatusPending)

Parse returns ErrEmptyEnum for "" and wraps ErrInvalidEnum otherwise, so errors.Is tells the two apart.

Comparison helpers

Thin wrappers that read better than == at a call site, and keep the enum type visible:

enumx.Is(s, StatusActive)                     // s == StatusActive
enumx.IsNot(s, StatusBlocked)                 // s != StatusBlocked
enumx.IsAny(s, StatusActive, StatusPending)   // s is one of them
enumx.Contains(s, StatusActive, StatusPending) // identical to IsAny

None of them consult the registry, so they answer the same way for an unregistered value: use IsValid when validity is the question.

Enum[T]: validation at every boundary

Embed the wrapper and the codecs come with it — no UnmarshalJSON, Scan, or Value to write:

type User struct {
    Status enumx.Enum[Status] `json:"status"`
}

Enum[T] implements:

Interface Effect
json.Marshaler / Unmarshaler rejects unregistered values in both directions
sql.Scanner / driver.Valuer validates on read and write; accepts string and []byte
encoding.TextMarshaler / TextUnmarshaler YAML, TOML, env decoders — and JSON map keys
fmt.Stringer the raw value
counts := map[enumx.Enum[Status]]int{{V: StatusActive}: 3}
json.Marshal(counts) // {"active":3}

NewEnum builds one from a value and reports whether it is registered, for the cases where you want the error rather than a later Valid() check:

e, err := enumx.NewEnum(StatusActive)

Prefer the free functions (enumx.MarshalJSON, enumx.UnmarshalJSON, enumx.Scan, enumx.Value) when you want the methods on your own type instead of a wrapper:

func (s Status) MarshalJSON() ([]byte, error)  { return enumx.MarshalJSON(s) }
func (s *Status) UnmarshalJSON(b []byte) error { return enumx.UnmarshalJSON(b, s) }
func (s *Status) Scan(src any) error           { return enumx.Scan(src, s) }
func (s Status) Value() (driver.Value, error)  { return enumx.Value(s) }

NullEnum[T]: when absent is a real state

For nullable columns and JSON fields where null is meaningful and distinct from invalid:

type User struct {
    Status enumx.NullEnum[Status] `json:"status"`
}

n.Get()                 // (value, present)
n.Or(StatusPending)     // value if present, fallback otherwise
n.String()              // "" when absent

Build one either way:

n, err := enumx.NewNullEnum(StatusActive) // present, validated against the registry
n = enumx.Null[Status]()                  // explicitly absent

NULL scans to absent, absent writes back as NULL, and JSON null round-trips. A failed scan or decode clears Valid, so a stale value can never be read as present.

Forgiving input

Parse is strict — right for internal data. For input you don’t control, ParseLoose tries, in order: an exact match, a registered alias, then a case- and separator-insensitive match.

enumx.RegisterAliases(StatusActive, "enabled", "on")

enumx.ParseLoose[Status]("ACTIVE")     // active
enumx.ParseLoose[Status]("enabled")    // active
enumx.ParseLoose[Status]("IN_REVIEW")  // in-review
enumx.ParseLoose[Status]("In Review")  // in-review

Aliases are matched the same way, so registering "in progress" also accepts "IN_PROGRESS". RegisterAliases panics if the target value is not registered.

Two more shortcuts:

enumx.MustParse[Status]("active")   // panics on failure — for package vars and tests
enumx.ParseOr(input, StatusPending) // falls back instead of failing