Documentation
ΒΆ
Index ΒΆ
- Variables
- func AddTransition[T ~string](from, to T)
- func CanTransition[T ~string](current, next T) bool
- func ClearFlag[T Integer](mask *T, flag T)
- func Contains[T ~string](val T, collection ...T) bool
- func Define(typeName string, values ...string) any
- func FormatFlags[T Integer](mask T) string
- func HasFlag[T Integer](mask, flag T) bool
- func Is[T ~string](val, target T) bool
- func IsAny[T ~string](val T, targets ...T) bool
- func IsNot[T ~string](val, target T) bool
- func IsValid[T ~string](val T) bool
- func LocaleLabel[T ~string](val T, locale string) string
- func MarshalJSON[T ~string](v T) ([]byte, error)
- func Match[T ~string, R any](val T, cases Cases[T, R]) R
- func Meta[T ~string, M any](val T) (M, bool)
- func Parse[T ~string](val string) (T, error)
- func ParseFlags[T Integer](s string) (T, error)
- func Register[T ~string](values ...T)
- func RegisterFlags[T Integer](flags map[T]string)
- func RegisterLocales[T ~string](val T, locales map[string]string)
- func RegisterMeta[T ~string, M any](val T, meta M)
- func RegisterTransitions[T ~string](transitions ...Transition[T])
- func Scan[T ~string](src any, v *T) error
- func SetFlag[T Integer](mask *T, flag T)
- func UnmarshalJSON[T ~string](b []byte, v *T) error
- func Value[T ~string](v T) (driver.Value, error)
- func Values[T ~string]() []T
- type Cases
- type Def
- type Enum
- type EnumValue
- type FlagSet
- type Integer
- type Matcher
- type MutableDef
- func (d *MutableDef[T]) Add(val T) *MutableDef[T]
- func (d *MutableDef[T]) Default(val T)
- func (d *MutableDef[T]) Has(val T) bool
- func (d *MutableDef[T]) IsDefault(val T) bool
- func (d *MutableDef[T]) Parse(val T) (EnumValue[T], error)
- func (d *MutableDef[T]) Remove(val T) *MutableDef[T]
- func (d *MutableDef[T]) Values() []T
- type Transition
Examples ΒΆ
Constants ΒΆ
This section is empty.
Variables ΒΆ
var ( // ErrInvalidEnum indicates that the enum value is not registered or valid. ErrInvalidEnum = errors.New("invalid enum value") // ErrEmptyEnum indicates that the enum value is empty. ErrEmptyEnum = errors.New("empty enum value") )
Functions ΒΆ
func AddTransition ΒΆ
func AddTransition[T ~string](from, to T)
AddTransition is a simplified helper to register a single state transition.
func CanTransition ΒΆ
CanTransition checks if moving from the current state to the next state is a registered valid transition.
func ClearFlag ΒΆ
func ClearFlag[T Integer](mask *T, flag T)
ClearFlag clears a specific flag from a bitmask.
func Contains ΒΆ
Contains checks if the enum value is within the provided collection. Functionally identical to IsAny, provided for API ergonomics.
func Define ΒΆ
Define is a marker function used exclusively by the enumx-gen code generator. It should only be used in files with the `//go:build ignore` directive. The first argument is the name of the generated Go type (e.g., "Status"). The remaining arguments are the enum values.
func FormatFlags ΒΆ
FormatFlags formats a bitmask into a string representation separated by " | ". If a flag is not registered, it is ignored in the output.
func IsValid ΒΆ
IsValid checks if the provided value is a valid, registered enum value. Returns false if the value is empty, not registered, or if the type itself hasn't been registered.
func LocaleLabel ΒΆ
LocaleLabel returns the localized label for an enum value given a locale code. If the locale is not found, it falls back to its raw string representation.
func MarshalJSON ΒΆ
MarshalJSON helps marshal an enum type T into a JSON string, ensuring it is valid. By default, Go automatically marshals underlying string types, but using this ensures invalid enum values are caught at marshal time.
Example:
func (s Status) MarshalJSON() ([]byte, error) {
return enumx.MarshalJSON(s)
}
func Match ΒΆ
Match performs an exhaustive switch-like check over the enum value. It ensures that all registered values of T are handled in the cases map. If a case is missing for a registered enum, it panics. If the provided value itself is invalid, it also panics. This provides a runtime guarantee of exhaustiveness, catching missing cases during tests.
Example ΒΆ
package main
import (
"fmt"
"github.com/bakhod1r/enumx"
)
type Role string
const RoleUser Role = "user"
func (r Role) Valid() bool { return enumx.IsValid(r) }
func (r *Role) UnmarshalJSON(b []byte) error { return enumx.UnmarshalJSON(b, r) }
func (r Role) MarshalJSON() ([]byte, error) { return enumx.MarshalJSON(r) }
func main() {
role := RoleUser
message := enumx.Match(role, enumx.Cases[Role, string]{
RoleAdmin: func() string { return "Welcome, Admin!" },
RoleUser: func() string { return "Welcome, User!" },
RoleGuest: func() string { return "Welcome, Guest!" },
})
fmt.Println(message)
}
Output: Welcome, User!
func Meta ΒΆ
Meta retrieves the custom metadata of type M attached to an enum value of type T. It returns the typed metadata and true if found, otherwise returns the zero value and false.
func Parse ΒΆ
Parse safely parses a string into the enum type T. It validates the string against the registered values for type T. Returns ErrEmptyEnum if the input string is empty. Returns ErrInvalidEnum (wrapped with context) if the value is not registered.
Example ΒΆ
package main
import (
"fmt"
"github.com/bakhod1r/enumx"
)
type Role string
func (r Role) Valid() bool { return enumx.IsValid(r) }
func (r *Role) UnmarshalJSON(b []byte) error { return enumx.UnmarshalJSON(b, r) }
func (r Role) MarshalJSON() ([]byte, error) { return enumx.MarshalJSON(r) }
func main() {
role, err := enumx.Parse[Role]("admin")
if err != nil {
panic(err)
}
fmt.Println(role)
}
Output: admin
func ParseFlags ΒΆ
ParseFlags parses a string separated by " | " into a bitmask of type T.
func Register ΒΆ
func Register[T ~string](values ...T)
Register registers the valid values for enum type T. This should be called in the init() function of the package where the enum is defined.
func RegisterFlags ΒΆ
RegisterFlags registers the string representations for bitmask flags of type T.
func RegisterLocales ΒΆ
RegisterLocales registers localized labels for a specific enum value. The locales argument is a map where the key is the locale code (e.g., "en", "uz") and the value is the translated label.
Example ΒΆ
package main
import (
"fmt"
"github.com/bakhod1r/enumx"
)
type Role string
const RoleAdmin Role = "admin"
func (r Role) Valid() bool { return enumx.IsValid(r) }
func (r *Role) UnmarshalJSON(b []byte) error { return enumx.UnmarshalJSON(b, r) }
func (r Role) MarshalJSON() ([]byte, error) { return enumx.MarshalJSON(r) }
func main() {
enumx.RegisterLocales(RoleAdmin, map[string]string{
"en": "Administrator",
"uz": "Tizim ma'muri",
})
fmt.Println(enumx.LocaleLabel(RoleAdmin, "uz"))
fmt.Println(enumx.LocaleLabel(RoleAdmin, "en"))
}
Output: Tizim ma'muri Administrator
func RegisterMeta ΒΆ
RegisterMeta attaches custom metadata of any type M to a specific enum value of type T.
func RegisterTransitions ΒΆ
func RegisterTransitions[T ~string](transitions ...Transition[T])
RegisterTransitions registers the allowed state transitions for enum type T. This is used to build a zero-allocation finite state machine (FSM).
func Scan ΒΆ
Scan helps implement the database/sql.Scanner interface. It parses the database value (typically string or []byte) into the enum type.
Example:
func (s *Status) Scan(src any) error {
return enumx.Scan(src, s)
}
func UnmarshalJSON ΒΆ
UnmarshalJSON helps safely unmarshal a JSON string into an enum type T. It should be called from the UnmarshalJSON method of the custom enum type.
Example:
func (s *Status) UnmarshalJSON(b []byte) error {
return enumx.UnmarshalJSON(b, s)
}
Example ΒΆ
package main
import (
"encoding/json"
"fmt"
"github.com/bakhod1r/enumx"
)
type Role string
const (
RoleAdmin Role = "admin"
RoleUser Role = "user"
RoleGuest Role = "guest"
)
func init() {
enumx.Register(RoleAdmin, RoleUser, RoleGuest)
}
func (r Role) Valid() bool { return enumx.IsValid(r) }
func (r *Role) UnmarshalJSON(b []byte) error { return enumx.UnmarshalJSON(b, r) }
func (r Role) MarshalJSON() ([]byte, error) { return enumx.MarshalJSON(r) }
func main() {
type Request struct {
UserRole Role `json:"role"`
}
validJSON := []byte(`{"role":"admin"}`)
var req Request
_ = json.Unmarshal(validJSON, &req)
fmt.Println("Parsed:", req.UserRole)
invalidJSON := []byte(`{"role":"hacker"}`)
var badReq Request
err := json.Unmarshal(invalidJSON, &badReq)
fmt.Println("Error:", err != nil)
}
Output: Parsed: admin Error: true
Types ΒΆ
type Def ΒΆ
type Def[T comparable] struct { // contains filtered or unexported fields }
Def is an immutable enum definition. Create it with New().
func New ΒΆ
func New[T comparable](vals ...T) *Def[T]
New creates an immutable enum definition from the provided values.
func (*Def[T]) Default ΒΆ
func (d *Def[T]) Default(val T)
Default sets the default value for the enum. Panics if val is not a registered member.
type Enum ΒΆ
type Enum[T ~string] struct { V T }
Enum is a generic wrapper struct that provides maximum convenience. By embedding this struct in your data models, you get automatic JSON and SQL validation without writing any boilerplate methods (UnmarshalJSON, Scan, etc.).
func (Enum[T]) MarshalJSON ΒΆ
MarshalJSON returns the JSON string representation of the enum.
func (Enum[T]) String ΒΆ
String returns the string representation. String returns the string representation.
func (*Enum[T]) UnmarshalJSON ΒΆ
UnmarshalJSON parses and validates the JSON string into the enum.
type EnumValue ΒΆ
type EnumValue[T comparable] struct { // contains filtered or unexported fields }
EnumValue is the result of a successful Parse call. It carries the validated value and provides a rich API.
type FlagSet ΒΆ
type FlagSet[T ~uint] struct { V T }
FlagSet is a wrapper for bitmask enums to provide a clean OOP API.
type Integer ΒΆ
type Integer interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
Integer defines a constraint that permits any integer type. This is used for bitmask flags.
type Matcher ΒΆ
Matcher is a builder for exhaustive matching.
func MatchBuilder ΒΆ
MatchBuilder creates a new Matcher builder for exhaustive evaluation. You must specify the return type R: enumx.MatchBuilder[Status, string](val)
type MutableDef ΒΆ
type MutableDef[T comparable] struct { // contains filtered or unexported fields }
MutableDef is a thread-safe, mutable enum definition. Create it with NewMutable().
func NewMutable ΒΆ
func NewMutable[T comparable](vals ...T) *MutableDef[T]
NewMutable creates a thread-safe, mutable enum definition.
func (*MutableDef[T]) Add ΒΆ
func (d *MutableDef[T]) Add(val T) *MutableDef[T]
Add appends val to the enum. Returns self for chaining.
func (*MutableDef[T]) Default ΒΆ
func (d *MutableDef[T]) Default(val T)
Default sets the default value for the enum.
func (*MutableDef[T]) Has ΒΆ
func (d *MutableDef[T]) Has(val T) bool
Has returns true if the value is a member of the mutable enum.
func (*MutableDef[T]) IsDefault ΒΆ
func (d *MutableDef[T]) IsDefault(val T) bool
IsDefault reports whether val equals the default value.
func (*MutableDef[T]) Parse ΒΆ
func (d *MutableDef[T]) Parse(val T) (EnumValue[T], error)
Parse validates val and returns a Value wrapping it, or an error.
func (*MutableDef[T]) Remove ΒΆ
func (d *MutableDef[T]) Remove(val T) *MutableDef[T]
Remove deletes val from the enum. Returns self for chaining.
func (*MutableDef[T]) Values ΒΆ
func (d *MutableDef[T]) Values() []T
Values returns all registered enum values in insertion order.
type Transition ΒΆ
type Transition[T ~string] struct { From T To T }
Transition represents a valid state transition from one enum value to another.