enum

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2026 License: MIT Imports: 3 Imported by: 0

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func MarshalJSON

func MarshalJSON[T ~string](val T, isValid func(T) bool, invalidErr error) ([]byte, error)

MarshalJSON marshals a string-based enum value to a JSON string. Returns the provided error if the value is invalid.

func Parse

func Parse[T ~string](s string, isValid func(T) bool, invalidErr error) (T, error)

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

func UnmarshalJSON[T ~string](
	data []byte,
	isValid func(T) bool,
	invalidErr error,
) (T, error)

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.

Jump to

Keyboard shortcuts

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