Documentation
ΒΆ
Overview ΒΆ
Package enum provides a type-safe and powerful enum implementation for Go, offering easy conversion between numeric and string representations.
It supports constant enums and integrates seamlessly with Go's `iota` enum pattern.
Features:
- No code generation
- Supports constant enums
- Easy value conversions
- Out of the box serialization
Index ΒΆ
- func All[Enum any]() []Enum
- func Finalize[Enum any]() bool
- func From[Enum any, P any](a P) (Enum, bool)
- func FromInt[Enum any](i int) (Enum, bool)
- func FromNumber[Enum any, N xreflect.Number](n N) (Enum, bool)
- func FromString[Enum any](s string) (Enum, bool)
- func IsValid[Enum any](value Enum) bool
- func Map[Enum any](enum Enum, reprs ...any) Enum
- func MarshalJSON[Enum any](value Enum) ([]byte, error)
- func MarshalXML[Enum any](encoder *xml.Encoder, start xml.StartElement, enum Enum) error
- func MarshalYAML[Enum any](value Enum) (any, error)
- func MustFrom[Enum any, P any](a P) Enum
- func MustFromInt[Enum any](i int) Enum
- func MustFromNumber[Enum any, N xreflect.Number](n N) Enum
- func MustFromString[Enum any](s string) Enum
- func MustTo[P, Enum any](enum Enum) P
- func NameOf[T any]() string
- func New[Enum any](reprs ...any) (enum Enum)
- func NewExtended[T newableEnum](reprs ...any) (enum T)
- func ScanSQL[Enum any](a any, value *Enum) error
- func To[P, Enum any](enum Enum) (P, bool)
- func ToInt[Enum any](enum Enum) int
- func ToString[Enum any](value Enum) string
- func TrueNameOf[T any]() string
- func UnmarshalJSON[Enum any](data []byte, t *Enum) (err error)
- func UnmarshalXML[Enum any](decoder *xml.Decoder, start xml.StartElement, enum *Enum) error
- func UnmarshalYAML[Enum any](value *yaml.Node, t *Enum) error
- func ValueSQL[Enum any](value Enum) (driver.Value, error)
- type Nullable
- func (e Nullable[Enum]) MarshalJSON() ([]byte, error)
- func (e Nullable[Enum]) MarshalYAML() (any, error)
- func (e *Nullable[Enum]) Scan(a any) error
- func (e *Nullable[Enum]) UnmarshalJSON(data []byte) error
- func (e *Nullable[Enum]) UnmarshalYAML(node *yaml.Node) error
- func (e Nullable[Enum]) Value() (driver.Value, error)
- type SafeEnum
- func (e SafeEnum[underlyingEnum]) GoString() string
- func (e SafeEnum[underlyingEnum]) Int() int
- func (e SafeEnum[underlyingEnum]) IsValid() bool
- func (e SafeEnum[underlyingEnum]) MarshalJSON() ([]byte, error)
- func (e SafeEnum[underlyingEnum]) MarshalXML(encoder *xml.Encoder, start xml.StartElement) error
- func (e SafeEnum[underlyingEnum]) MarshalYAML() (any, error)
- func (e *SafeEnum[underlyingEnum]) Scan(a any) error
- func (e SafeEnum[underlyingEnum]) String() string
- func (e SafeEnum[underlyingEnum]) To() underlyingEnum
- func (e *SafeEnum[underlyingEnum]) UnmarshalJSON(data []byte) error
- func (e *SafeEnum[underlyingEnum]) UnmarshalXML(decoder *xml.Decoder, start xml.StartElement) error
- func (e *SafeEnum[underlyingEnum]) UnmarshalYAML(node *yaml.Node) error
- func (e SafeEnum[underlyingEnum]) Value() (driver.Value, error)
- type WrapEnum
- func (e WrapEnum[underlyingEnum]) GoString() string
- func (e WrapEnum[underlyingEnum]) Int() int
- func (e WrapEnum[underlyingEnum]) IsValid() bool
- func (e WrapEnum[underlyingEnum]) MarshalJSON() ([]byte, error)
- func (e WrapEnum[underlyingEnum]) MarshalXML(encoder *xml.Encoder, start xml.StartElement) error
- func (e WrapEnum[underlyingEnum]) MarshalYAML() (any, error)
- func (e *WrapEnum[underlyingEnum]) Scan(a any) error
- func (e WrapEnum[underlyingEnum]) String() string
- func (e WrapEnum[underlyingEnum]) To() underlyingEnum
- func (e *WrapEnum[underlyingEnum]) UnmarshalJSON(data []byte) error
- func (e *WrapEnum[underlyingEnum]) UnmarshalXML(decoder *xml.Decoder, start xml.StartElement) error
- func (e *WrapEnum[underlyingEnum]) UnmarshalYAML(node *yaml.Node) error
- func (e WrapEnum[underlyingEnum]) Value() (driver.Value, error)
- type WrapFloatEnum
- func (e WrapFloatEnum[underlyingEnum]) GoString() string
- func (e WrapFloatEnum[underlyingEnum]) IsValid() bool
- func (e WrapFloatEnum[underlyingEnum]) MarshalJSON() ([]byte, error)
- func (e WrapFloatEnum[underlyingEnum]) MarshalXML(encoder *xml.Encoder, start xml.StartElement) error
- func (e WrapFloatEnum[underlyingEnum]) MarshalYAML() (any, error)
- func (e *WrapFloatEnum[underlyingEnum]) Scan(a any) error
- func (e WrapFloatEnum[underlyingEnum]) String() string
- func (e WrapFloatEnum[underlyingEnum]) To() underlyingEnum
- func (e *WrapFloatEnum[underlyingEnum]) UnmarshalJSON(data []byte) error
- func (e *WrapFloatEnum[underlyingEnum]) UnmarshalXML(decoder *xml.Decoder, start xml.StartElement) error
- func (e *WrapFloatEnum[underlyingEnum]) UnmarshalYAML(node *yaml.Node) error
- func (e WrapFloatEnum[underlyingEnum]) Value() (driver.Value, error)
- type WrapUintEnum
- func (e WrapUintEnum[underlyingEnum]) GoString() string
- func (e WrapUintEnum[underlyingEnum]) IsValid() bool
- func (e WrapUintEnum[underlyingEnum]) MarshalJSON() ([]byte, error)
- func (e WrapUintEnum[underlyingEnum]) MarshalXML(encoder *xml.Encoder, start xml.StartElement) error
- func (e WrapUintEnum[underlyingEnum]) MarshalYAML() (any, error)
- func (e *WrapUintEnum[underlyingEnum]) Scan(a any) error
- func (e WrapUintEnum[underlyingEnum]) String() string
- func (e WrapUintEnum[underlyingEnum]) To() underlyingEnum
- func (e *WrapUintEnum[underlyingEnum]) UnmarshalJSON(data []byte) error
- func (e *WrapUintEnum[underlyingEnum]) UnmarshalXML(decoder *xml.Decoder, start xml.StartElement) error
- func (e *WrapUintEnum[underlyingEnum]) UnmarshalYAML(node *yaml.Node) error
- func (e WrapUintEnum[underlyingEnum]) Value() (driver.Value, error)
Examples ΒΆ
Constants ΒΆ
This section is empty.
Variables ΒΆ
This section is empty.
Functions ΒΆ
func All ΒΆ
func All[Enum any]() []Enum
All returns a slice containing all enum values of a specific type.
func From ΒΆ
From returns the corresponding enum for a given representation, and whether it is valid.
func FromInt ΒΆ
FromInt returns the corresponding enum for a given int representation, and whether it is valid.
DEPRECATED: Use FromNumber instead.
func FromNumber ΒΆ
FromNumber returns the corresponding enum for a given number representation, and whether it is valid.
func FromString ΒΆ
FromString returns the corresponding enum for a given string representation, and whether it is valid.
func IsValid ΒΆ
IsValid checks if an enum value is valid. It returns true if the enum value is valid, and false otherwise.
func Map ΒΆ
Map associates an enum with its representations under strict rules:
- String enums map to themselves as the string representation; Stringer is also treated as a string representation if no string repr is found.
- Numeric enums map to themselves as the numeric representation; all primitive numeric types (ints, uints, floats) are treated as a single type.
- An enum cannot be mapped to multiple representations of the same type.
Note that this function is not thread-safe and should only be called during initialization or other safe execution points to avoid race conditions.
Example ΒΆ
package main import ( "fmt" "github.com/anypine/enum" ) func main() { type Role int // Define enum values for Role using iota. const ( RoleUser Role = iota RoleAdmin ) // Map string representations to enum values. var ( _ = enum.Map(RoleUser, "user") _ = enum.Map(RoleAdmin, "admin") _ = enum.Finalize[Role]() ) // Print all enum values. for _, e := range enum.All[Role]() { fmt.Println(enum.ToString(e)) } }
Output: user admin
func MarshalJSON ΒΆ
MarshalJSON serializes an enum value into its string representation.
func MarshalXML ΒΆ
MarshalXML converts enum to its string representation.
func MarshalYAML ΒΆ
MarshalYAML serializes an enum value into its string representation.
func MustFrom ΒΆ
MustFrom returns the corresponding enum for a given representation. It returns the zero value of enum in case the representation is unknown.
func MustFromInt ΒΆ
MustFromInt returns the corresponding enum for a given int representation.
It returns zero value if the enum value is invalid.
DEPRECATED: Use MustFromNumber instead.
func MustFromNumber ΒΆ
MustFromNumber returns the corresponding enum for a given number representation.
It returns the zero value if the enum value is invalid.
func MustFromString ΒΆ
MustFromString returns the corresponding enum for a given string representation.
It returns zero value if the string does not correspond to a valid enum value.
func MustTo ΒΆ
func MustTo[P, Enum any](enum Enum) P
MustTo returns the representation (the type is relied on P type parameter) for the given enum value. It returns zero value if the enum is invalid or the enum doesn't have any representation of type P.
func NameOf ΒΆ
NameOf returns the name of the enum type. In case of this is an advanced enum provided by this library, this function returns the only underlying enum name, which differs from TrueNameOf.
For example:
NameOf[Role]() = "Role" NameOf[WrapEnum[role]]() = "Role"
func New ΒΆ
New creates a dynamic enum value then mapped to its representations. The Enum type must be a number, string, or supported enums (e.g WrapEnum, SafeEnum).
If the enum is
- Supported enum: the inner new function will be called to generate the enum value.
- Number: the numeric representation will be assigned to the enum value.
- String: the string representation will be assigned to the enum value.
- Other cases, panics.
Note that this function is not thread-safe and should only be called during initialization or other safe execution points to avoid race conditions.
Example ΒΆ
package main import ( "fmt" "github.com/anypine/enum" ) func main() { type Role int // Define enum values for Role. var ( RoleUser = enum.New[Role]("user") RoleAdmin = enum.New[Role]("admin") _ = enum.Finalize[Role]() ) // Print the string representation of enum values. fmt.Println("string(RoleUser):", enum.ToString(RoleUser)) fmt.Println("string(RoleAdmin):", enum.ToString(RoleAdmin)) // Demonstrate converting string to enum value. fmt.Println(`enum("user"):`, enum.MustFromString[Role]("user")) fmt.Println(`enum("admin"):`, enum.MustFromString[Role]("admin")) }
Output: string(RoleUser): user string(RoleAdmin): admin enum("user"): 0 enum("admin"): 1
func NewExtended ΒΆ
func NewExtended[T newableEnum](reprs ...any) (enum T)
NewExtended initializes an extended enum then mapped to its representations.
An extended enum follows this structure (the embedded Enum must be an anonymous field to inherit its built-in methods):
type role any type Role struct { enum.SafeEnum[role] }
Note that this function is not thread-safe and should only be called during initialization or other safe execution points to avoid race conditions.
func To ΒΆ
To returns the representation (the type is relied on P type parameter) for the given enum value. The latter returned value is false if the enum is invalid or the enum doesn't have any representation of type P.
func ToInt ΒΆ
ToInt returns the int representation for the given enum value. It returns the smallest value of int (math.MinInt32) for invalid enums.
DEPRECATED: This function returns math.MinInt32 for invalid enums, which may cause unexpected behavior. Use To() or MustTo() instead.
func ToString ΒΆ
ToString returns the string representation of the given enum value. It returns <nil> for invalid enums.
func TrueNameOf ΒΆ
TrueNameOf returns the name of the enum type. In case of this is an advanced enum provided by this library, this function returns the full name, which differs from NameOf.
For example:
TrueNameOf[Role]() = "Role" TrueNameOf[WrapEnum[role]]() = "WrapEnum[role]"
func UnmarshalJSON ΒΆ
UnmarshalJSON deserializes a string representation of an enum value from JSON.
func UnmarshalXML ΒΆ
UnmarshalXML parses the string representation back into an enum.
func UnmarshalYAML ΒΆ
UnmarshalYAML deserializes a string representation of an enum value from YAML.
Types ΒΆ
type Nullable ΒΆ
Nullable allows handling nullable enums in JSON, YAML, and SQL.
Example ΒΆ
package main import ( "encoding/json" "fmt" "github.com/anypine/enum" ) func main() { type Role int type NullRole = enum.Nullable[Role] var ( _ = enum.New[Role]("user") RoleAdmin = enum.New[Role]("admin") _ = enum.Finalize[Role]() ) // Define a struct that includes the Role enum. type User struct { ID int `json:"id"` Name string `json:"name"` Role NullRole `json:"role"` } // Serialize zero struct data, _ := json.Marshal(User{}) fmt.Println(string(data)) // Serialize the User struct to JSON. user1 := User{ID: 0, Name: "tester", Role: NullRole{Enum: RoleAdmin, Valid: true}} data, _ = json.Marshal(user1) fmt.Println(string(data)) }
Output: {"id":0,"name":"","role":null} {"id":0,"name":"tester","role":"admin"}
func (Nullable[Enum]) MarshalJSON ΒΆ
func (Nullable[Enum]) MarshalYAML ΒΆ
func (*Nullable[Enum]) UnmarshalJSON ΒΆ
func (*Nullable[Enum]) UnmarshalYAML ΒΆ
type SafeEnum ΒΆ
type SafeEnum[underlyingEnum any] struct { // contains filtered or unexported fields }
SafeEnum defines a strong type-safe enum. Like WrapEnum, it provides a set of built-in methods to simplify working with enums. However, it doesn't support constant value.
The SafeEnum enforces strict type safety, ensuring that only predefined enum values are allowed. It prevents the accidental creation of new enum types, providing a guaranteed set of valid values.
Example ΒΆ
package main import ( "encoding/json" "fmt" "github.com/anypine/enum" ) func main() { type role string type Role = enum.SafeEnum[role] var ( RoleUser = enum.New[Role]("user") RoleAdmin = enum.New[Role]("admin") _ = enum.Finalize[Role]() ) // As Role is a SafeEnum, it can utilize methods from SafeEnum, including // utility functions and serde operations. fmt.Println(RoleUser.GoString()) // 0 (user) fmt.Println(RoleUser.IsValid()) // true // Define a struct that includes the Role enum. type User struct { ID int `json:"id"` Name string `json:"name"` Role Role `json:"role"` } // Serialize zero struct data, err := json.Marshal(User{}) if err != nil { fmt.Println("cannot serialize zero struct") } // Serialize the User struct to JSON. user1 := User{ID: 0, Name: "tester", Role: RoleAdmin} data, _ = json.Marshal(user1) fmt.Println(string(data)) // Deserialize JSON back into a User struct and print the Role. user2 := User{} json.Unmarshal(data, &user2) fmt.Println(user2.Role) }
Output: 0 (user) true cannot serialize zero struct {"id":0,"name":"tester","role":"admin"} admin
func (SafeEnum[underlyingEnum]) MarshalJSON ΒΆ
func (SafeEnum[underlyingEnum]) MarshalXML ΒΆ
func (SafeEnum[underlyingEnum]) MarshalYAML ΒΆ
func (SafeEnum[underlyingEnum]) To ΒΆ
func (e SafeEnum[underlyingEnum]) To() underlyingEnum
To returns the underlying representation of this enum.
func (*SafeEnum[underlyingEnum]) UnmarshalJSON ΒΆ
func (*SafeEnum[underlyingEnum]) UnmarshalXML ΒΆ
func (*SafeEnum[underlyingEnum]) UnmarshalYAML ΒΆ
type WrapEnum ΒΆ
WrapEnum provides a set of built-in methods to simplify working with int enums.
Example ΒΆ
package main import ( "encoding/json" "fmt" "github.com/anypine/enum" ) func main() { type role any type Role = enum.WrapEnum[role] // Define enum values for Role using iota const ( RoleUser Role = iota RoleAdmin ) // Map string representations to enum values var ( _ = enum.Map(RoleUser, "user") _ = enum.Map(RoleAdmin, "admin") _ = enum.Finalize[Role]() ) // Define a struct that includes the Role enum. type User struct { ID int `json:"id"` Name string `json:"name"` Role Role `json:"role"` } // Serialize zero struct data, _ := json.Marshal(User{}) fmt.Println(string(data)) // Serialize the User struct to JSON. user1 := User{ID: 0, Name: "tester", Role: RoleAdmin} data, _ = json.Marshal(user1) fmt.Println(string(data)) // Deserialize JSON back into a User struct and print the Role. user2 := User{} json.Unmarshal(data, &user2) fmt.Println(user2.Role) }
Output: {"id":0,"name":"","role":"user"} {"id":0,"name":"tester","role":"admin"} admin
func (WrapEnum[underlyingEnum]) Int ΒΆ
Int returns the int representation of the enum. This method returns the value of math.MinInt32 if the enum is invalid.
DEPRECATED: directly cast the enum to int instead.
func (WrapEnum[underlyingEnum]) MarshalJSON ΒΆ
func (WrapEnum[underlyingEnum]) MarshalXML ΒΆ
func (WrapEnum[underlyingEnum]) MarshalYAML ΒΆ
func (WrapEnum[underlyingEnum]) To ΒΆ
func (e WrapEnum[underlyingEnum]) To() underlyingEnum
To returns the underlying representation of this enum.
func (*WrapEnum[underlyingEnum]) UnmarshalJSON ΒΆ
func (*WrapEnum[underlyingEnum]) UnmarshalXML ΒΆ
func (*WrapEnum[underlyingEnum]) UnmarshalYAML ΒΆ
type WrapFloatEnum ΒΆ
WrapFloatEnum provides a set of built-in methods to simplify working with float64 enums.
func (WrapFloatEnum[underlyingEnum]) GoString ΒΆ
func (e WrapFloatEnum[underlyingEnum]) GoString() string
func (WrapFloatEnum[underlyingEnum]) IsValid ΒΆ
func (e WrapFloatEnum[underlyingEnum]) IsValid() bool
func (WrapFloatEnum[underlyingEnum]) MarshalJSON ΒΆ
func (e WrapFloatEnum[underlyingEnum]) MarshalJSON() ([]byte, error)
func (WrapFloatEnum[underlyingEnum]) MarshalXML ΒΆ
func (e WrapFloatEnum[underlyingEnum]) MarshalXML(encoder *xml.Encoder, start xml.StartElement) error
func (WrapFloatEnum[underlyingEnum]) MarshalYAML ΒΆ
func (e WrapFloatEnum[underlyingEnum]) MarshalYAML() (any, error)
func (*WrapFloatEnum[underlyingEnum]) Scan ΒΆ
func (e *WrapFloatEnum[underlyingEnum]) Scan(a any) error
func (WrapFloatEnum[underlyingEnum]) String ΒΆ
func (e WrapFloatEnum[underlyingEnum]) String() string
func (WrapFloatEnum[underlyingEnum]) To ΒΆ
func (e WrapFloatEnum[underlyingEnum]) To() underlyingEnum
To returns the underlying representation of this enum.
func (*WrapFloatEnum[underlyingEnum]) UnmarshalJSON ΒΆ
func (e *WrapFloatEnum[underlyingEnum]) UnmarshalJSON(data []byte) error
func (*WrapFloatEnum[underlyingEnum]) UnmarshalXML ΒΆ
func (e *WrapFloatEnum[underlyingEnum]) UnmarshalXML(decoder *xml.Decoder, start xml.StartElement) error
func (*WrapFloatEnum[underlyingEnum]) UnmarshalYAML ΒΆ
func (e *WrapFloatEnum[underlyingEnum]) UnmarshalYAML(node *yaml.Node) error
type WrapUintEnum ΒΆ
WrapUintEnum provides a set of built-in methods to simplify working with uint enums.
func (WrapUintEnum[underlyingEnum]) GoString ΒΆ
func (e WrapUintEnum[underlyingEnum]) GoString() string
func (WrapUintEnum[underlyingEnum]) IsValid ΒΆ
func (e WrapUintEnum[underlyingEnum]) IsValid() bool
func (WrapUintEnum[underlyingEnum]) MarshalJSON ΒΆ
func (e WrapUintEnum[underlyingEnum]) MarshalJSON() ([]byte, error)
func (WrapUintEnum[underlyingEnum]) MarshalXML ΒΆ
func (e WrapUintEnum[underlyingEnum]) MarshalXML(encoder *xml.Encoder, start xml.StartElement) error
func (WrapUintEnum[underlyingEnum]) MarshalYAML ΒΆ
func (e WrapUintEnum[underlyingEnum]) MarshalYAML() (any, error)
func (*WrapUintEnum[underlyingEnum]) Scan ΒΆ
func (e *WrapUintEnum[underlyingEnum]) Scan(a any) error
func (WrapUintEnum[underlyingEnum]) String ΒΆ
func (e WrapUintEnum[underlyingEnum]) String() string
func (WrapUintEnum[underlyingEnum]) To ΒΆ
func (e WrapUintEnum[underlyingEnum]) To() underlyingEnum
To returns the underlying representation of this enum.
func (*WrapUintEnum[underlyingEnum]) UnmarshalJSON ΒΆ
func (e *WrapUintEnum[underlyingEnum]) UnmarshalJSON(data []byte) error
func (*WrapUintEnum[underlyingEnum]) UnmarshalXML ΒΆ
func (e *WrapUintEnum[underlyingEnum]) UnmarshalXML(decoder *xml.Decoder, start xml.StartElement) error
func (*WrapUintEnum[underlyingEnum]) UnmarshalYAML ΒΆ
func (e *WrapUintEnum[underlyingEnum]) UnmarshalYAML(node *yaml.Node) error