enum

package
v0.0.0-...-6b1ce1c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 29, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrEnumValueInvalid = errors.New("enum value is not in valid list")
	ErrInvalidEnumValue = errors.New("invalid enum value")
)

Static errors for enum validation.

Functions

func EnumNames

func EnumNames[T ~string](enums ...T) []string

EnumNames returns string names of enum values.

func EnumToStringSlice

func EnumToStringSlice[T ~string](enums ...T) []string

EnumToStringSlice converts enum values to string slice.

func MarshalJSON

func MarshalJSON[T ~string](value T, validValues ...T) ([]byte, error)

MarshalJSON provides generic JSON marshaling for enum types. Usage: implement MarshalJSON on your enum type like this:

func (e MyEnum) MarshalJSON() ([]byte, error) {
	return enum.MarshalJSON(e, MyEnumValue1, MyEnumValue2)
}

func MarshalJSONForInterface

func MarshalJSONForInterface[T EnumType](value T, typeName string) ([]byte, error)

MarshalJSONForInterface marshals JSON using the EnumType interface. This is useful for enums that implement their own IsValid method.

func ParseEnum

func ParseEnum[T ~string](str string, defaultValue T, validValues ...T) T

ParseEnum parses a string into an enum type with validation.

func UnmarshalJSON

func UnmarshalJSON[T ~string](
	dest *T,
	data []byte,
	typeName string,
	defaultValue T,
	validValues ...T,
) error

func UnmarshalJSONForInterface

func UnmarshalJSONForInterface[T EnumType](dest *T, data []byte, typeName string) error

UnmarshalJSONForInterface unmarshals JSON using the EnumType interface. This is useful for enums that implement their own IsValid method.

func UnmarshalJSONFromStrings

func UnmarshalJSONFromStrings[T ~string](
	dest *T,
	data []byte,
	typeName string,
	defaultValue T,
	validStrings []string,
) error

UnmarshalJSONFromStrings unmarshals JSON using a string slice for validation.

func ValidateEnum

func ValidateEnum[T ~string](value T, validValues ...T) bool

ValidateEnum checks if an enum value is in the list of valid values.

Types

type EnumType

type EnumType interface {
	IsValid() bool
	String() string
}

EnumType defines common interface for all enum-like types with IsValid method.

type StringEnum

type StringEnum string

StringEnum is a generic type for string-based enums.

func (StringEnum) String

func (se StringEnum) String() string

String returns the string value of the enum.

type ValidatableEnum

type ValidatableEnum interface {
	IsValid() bool
}

ValidatableEnum interface for enums that can validate themselves.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL