Documentation
¶
Overview ¶
Package enum provides generic helpers for string-based enum types, eliminating boilerplate IsValid/MarshalJSON/UnmarshalJSON/Parse methods.
Usage:
type Color string
const (
Red Color = "red"
Green Color = "green"
Blue Color = "blue"
)
func (c Color) IsValid() bool {
switch c {
case Red, Green, Blue:
return true
default:
return false
}
}
func (c Color) MarshalJSON() ([]byte, error) {
return enum.MarshalJSON(c, c.IsValid, ErrInvalidColor)
}
Index ¶
- func MarshalJSON[T ~string](val T, isValid func(T) bool, invalidErr error) ([]byte, error)
- func Parse[T ~string](s string, isValid func(T) bool, invalidErr error) (T, error)
- func UnmarshalJSON[T ~string](data []byte, isValid func(T) bool, invalidErr error) (T, error)
- func UnmarshalJSONInto[T ~string](dst *T, data []byte, isValid func(T) bool, invalidErr error) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func MarshalJSON ¶
MarshalJSON marshals a string-based enum value to a JSON string. Returns the provided error if the value is invalid.
func Parse ¶
Parse converts a raw string to an enum value with validation. Returns the provided error if the string is not a valid enum value.
func UnmarshalJSON ¶
UnmarshalJSON unmarshals JSON data into a string-based enum value. Returns the provided error if the parsed value is invalid.
func UnmarshalJSONInto ¶
func UnmarshalJSONInto[T ~string]( dst *T, data []byte, isValid func(T) bool, invalidErr error, ) error
UnmarshalJSONInto is the pointer-receiver UnmarshalJSON companion to UnmarshalJSON. It handles the boilerplate that every string-based enum type repeats:
func (t *T) UnmarshalJSON(data []byte) error {
parsed, err := enum.UnmarshalJSON(data, T.IsValid, ErrInvalidT)
if err != nil {
return err
}
*t = parsed
return nil
}
The wrapper avoids that ceremony at every enum declaration site.
Types ¶
This section is empty.