Documentation
¶
Index ¶
- Constants
- func InitFor[T EnumBase, R any]() R
- type CascaderOption
- type Enum
- func (e *Enum[T]) AddExt(itemKey, extKey, extValue string)
- func (e *Enum[T]) All() []Item[T]
- func (e *Enum[T]) ByKey(key string) (Item[T], bool)
- func (e *Enum[T]) ByValue(value T) (Item[T], bool)
- func (e *Enum[T]) Contains(value T) bool
- func (e *Enum[T]) GetExt(itemKey string) map[string]string
- func (e *Enum[T]) Index(i int) (Item[T], bool)
- func (e *Enum[T]) Keys() []string
- func (e *Enum[T]) Len() int
- func (e *Enum[T]) MarshalJSON() ([]byte, error)
- func (e *Enum[T]) MustByKey(key string) Item[T]
- func (e *Enum[T]) MustByValue(value T) Item[T]
- func (e *Enum[T]) MustIndex(i int) Item[T]
- func (e *Enum[T]) Range() iter.Seq2[string, Item[T]]
- func (e *Enum[T]) ToMap() map[string]map[string]any
- func (e *Enum[T]) UnmarshalJSON(data []byte) error
- func (e *Enum[T]) Values() []T
- type EnumBase
- type Item
- type ItemOption
- type Struct
- func (s *Struct[T]) AddExt(itemKey, extKey, extValue string)
- func (s *Struct[T]) All() []Item[T]
- func (s *Struct[T]) ByKey(name string) (Item[T], bool)
- func (s *Struct[T]) ByValue(value T) (Item[T], bool)
- func (s *Struct[T]) Contains(value T) bool
- func (s *Struct[T]) Enum() *Enum[T]
- func (s *Struct[T]) GetExt(itemKey string) map[string]string
- func (s *Struct[T]) Index(i int) (Item[T], bool)
- func (s *Struct[T]) Keys() []string
- func (s *Struct[T]) Len() int
- func (s *Struct[T]) MarshalJSON() ([]byte, error)
- func (s *Struct[T]) MustByKey(name string) Item[T]
- func (s *Struct[T]) MustByValue(value T) Item[T]
- func (s *Struct[T]) MustIndex(i int) Item[T]
- func (s *Struct[T]) Range() iter.Seq2[string, Item[T]]
- func (s *Struct[T]) ToMap() map[string]map[string]any
- func (s *Struct[T]) Tree() []TreeNode
- func (s *Struct[T]) TreeOptions() []CascaderOption
- func (s *Struct[T]) UnmarshalJSON(data []byte) error
- func (s *Struct[T]) Values() []T
- type TreeNode
Examples ¶
Constants ¶
const ( NameKey = "name" ValueKey = "value" DisabledKey = "disabled" ExtKey = "ext" )
JSON field names shared between jsonItem struct tags and ToMap output.
const ParentExtKey = "parent"
ParentExtKey is the ext key used by BuildTree to establish parent-child relationships. Items with ext[ParentExtKey] == "…" are treated as children of the item with the matching value.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type CascaderOption ¶ added in v0.2.0
type CascaderOption struct {
Label string `json:"label"`
Value string `json:"value"`
Disabled bool `json:"disabled,omitempty"`
Children []CascaderOption `json:"children,omitempty"`
}
CascaderOption is the Ant Design <Cascader> / <TreeSelect> format, using label instead of name. Produced by Struct[T].TreeOptions().
type Enum ¶
type Enum[T EnumBase] struct { // contains filtered or unexported fields }
Enum is an ordered set of named values. It is logically immutable — items, names, and values are fixed after construction. The only exception is AddExt, which mutates the extension metadata of an existing item; all other fields remain stable.
It is safe for concurrent use after construction, provided AddExt calls are not concurrent with reads.
Example (RoundTrip) ¶
// Create, marshal, unmarshal back — end-to-end.
e := enum.InitFor[OrderStatus, OrderStatuses]()
e.AddExt("Processing", "color", "blue")
// Marshal.
b, _ := json.Marshal(e.Enum())
// Unmarshal into a fresh Enum.
var restored enum.Enum[OrderStatus]
json.Unmarshal(b, &restored)
// Verify.
item, _ := restored.ByKey("Processing")
fmt.Println(item.Name(), item.Ext()["color"])
Output: 处理中 blue
func New ¶
New creates an Enum from the given items. Panics if no items are provided, or if any name or value is duplicated.
func (*Enum[T]) AddExt ¶
AddExt adds a key-value pair to the named item's extension metadata. No-op when the item is not found. The item's ext map is created on first use. Updates both the items slice and the lookup maps so subsequent ByKey/ByValue calls reflect the change. Panics if the item does not exist — a typo'd key would otherwise be silently ignored, hiding a bug from the caller.
func (*Enum[T]) ByKey ¶
ByKey returns the item with the given key. The second return value is false when the key does not exist.
func (*Enum[T]) ByValue ¶
ByValue returns the item with the given value. The second return value is false when the value does not exist.
func (*Enum[T]) GetExt ¶
GetExt returns a copy of the named item's extension metadata, or nil when the item is not found.
func (*Enum[T]) Index ¶
Index returns the item at the given position in definition order. The second return value is false when i is out of range.
func (*Enum[T]) MarshalJSON ¶
MarshalJSON serializes the enum as an ordered array of {key, name, value, disabled?, ext?}.
Example (Int) ¶
statuses := enum.InitFor[OrderStatus, OrderStatuses]() b, _ := json.Marshal(statuses.Enum()) fmt.Println(string(b))
Output: [{"key":"Pending","name":"待处理","value":0},{"key":"Processing","name":"处理中","value":1},{"key":"Shipped","name":"已发货","value":2},{"key":"Cancelled","name":"已取消","value":3,"disabled":true}]
Example (String) ¶
e := enum.InitFor[Severity, SeverityEnum]() b, _ := json.Marshal(e.Enum()) fmt.Println(string(b))
Output: [{"key":"Info","name":"信息","value":"INFO"},{"key":"Warn","name":"警告","value":"WARN"},{"key":"Error","name":"错误","value":"ERROR"}]
func (*Enum[T]) MustByKey ¶
MustByKey returns the item with the given key, panicking if it doesn't exist.
func (*Enum[T]) MustByValue ¶
MustByValue returns the item with the given value, panicking if it doesn't exist.
func (*Enum[T]) ToMap ¶
ToMap returns each item keyed by its key. Useful when the frontend needs O(1) lookup by key instead of array iteration:
json.NewEncoder(w).Encode(event.Events.ToMap())
// → {UserCreated: {name:"用户创建", value:"user.created"}, ...}
Example ¶
ToMap as JSON.
e := enum.InitFor[Severity, SeverityEnum]() b, _ := json.Marshal(e.ToMap()) fmt.Println(string(b))
Output: {"Error":{"name":"错误","value":"ERROR"},"Info":{"name":"信息","value":"INFO"},"Warn":{"name":"警告","value":"WARN"}}
func (*Enum[T]) UnmarshalJSON ¶
UnmarshalJSON reconstructs the enum from a JSON array. Returns an error on duplicate names/values or invalid JSON.
Example ¶
data := []byte(`[{"key":"Low","name":"低","value":0},{"key":"High","name":"高","value":2}]`)
var e enum.Enum[Priority]
if err := json.Unmarshal(data, &e); err != nil {
panic(err)
}
item, _ := e.ByKey("High")
fmt.Println("found:", item.Name(), "→", item.Value())
Output: found: 高 → 2
type EnumBase ¶
type EnumBase interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~string
}
EnumBase is the type constraint for enum value types. Only int/uint/string-based types are supported.
type Item ¶
type Item[T EnumBase] struct { // contains filtered or unexported fields }
Item is one member of an enum—a programmatic key, a human-readable name, and a value. Fields are private; use the accessor methods to read them.
func AsStringItems ¶
AsStringItems converts a typed Item slice to []Item[string] using fmt.Sprint for the value. This allows combining items from different enum types into a single BuildTree input.
func ItemFrom ¶
func ItemFrom[T EnumBase](key, name string, value T, opts ...ItemOption[T]) Item[T]
ItemFrom creates an Item. key is the programmatic identifier (e.g. "Monday"); name is the human-readable label (e.g. "周一"). Options like WithDisabled and WithExt are applied last.
func (Item[T]) IsDisabled ¶
type ItemOption ¶
ItemOption is a functional option for ItemFrom.
func WithDisabled ¶
func WithDisabled[T EnumBase]() ItemOption[T]
WithDisabled marks the item as disabled (display-only, not selectable).
type Struct ¶
type Struct[T EnumBase] struct { // contains filtered or unexported fields }
Struct is a reflection-driven enum backed by Enum[T]. Use InitFor:
type Statuses struct {
Struct[Status] // embed anywhere (found by scanning anonymous fields)
Pending Status `enum:"0,待处理"`
Active Status `enum:"1,活跃"`
}
s := enum.InitFor[Status, Statuses]()
s.ByKey("Active") // → Item, true
switch v { case s.Pending: ... }
Example (Embedded_marshal) ¶
e := enum.InitFor[Severity, SeverityEnum]() b, _ := json.Marshal(e.Enum()) var items []map[string]any json.Unmarshal(b, &items) fmt.Println(items[0]["key"], items[0]["name"])
Output: Info 信息
Example (Embedded_unmarshal) ¶
// Unmarshal replaces the underlying enum data.
data := []byte(`[{"key":"A","name":"甲","value":1}]`)
var e enum.Enum[Priority]
json.Unmarshal(data, &e)
fmt.Println(e.Len(), e.Contains(Priority(1)))
Output: 1 true
func (*Struct[T]) Enum ¶
Enum returns the underlying Enum[T]. When Struct is embedded in another struct that has its own exported fields, Go's JSON encoder ignores the embedded MarshalJSON/UnmarshalJSON — use .Enum() to serialize/deserialize directly:
json.NewEncoder(w).Encode(event.Events.Enum()) // marshal json.NewDecoder(r).Decode(event.Events.Enum()) // unmarshal
Returns nil when the Struct has not been initialized via InitFor.
func (*Struct[T]) MarshalJSON ¶
MarshalJSON / UnmarshalJSON delegate to the underlying enum. They return an error (rather than panic) when the Struct is uninitialized.
Example ¶
p := enum.InitFor[Priority, Priorities]() b, _ := json.Marshal(p) fmt.Println(string(b))
Output: {"Low":0,"Medium":1,"High":2}
Example (Struct) ¶
p := enum.InitFor[Priority, Priorities]() sb, _ := json.Marshal(p.Struct) fmt.Println(string(sb))
Output: {}
func (*Struct[T]) MustByValue ¶
func (*Struct[T]) TreeOptions ¶ added in v0.2.0
func (s *Struct[T]) TreeOptions() []CascaderOption
TreeOptions converts the tree to Ant Design Cascader format.
func (*Struct[T]) UnmarshalJSON ¶
type TreeNode ¶
type TreeNode struct {
Key string `json:"key"`
Name string `json:"name"`
Value string `json:"value"`
Disabled bool `json:"disabled,omitempty"`
Children []TreeNode `json:"children,omitempty"`
}
TreeNode is a recursive frontend node for multi-level dropdowns.
func BuildTree ¶
BuildTree converts a flat item list into a recursive tree keyed by ext["parent"]. Items without a parent (or whose parent doesn't match any item) become roots.
Example ¶
BuildTree produces nested JSON for multi-level dropdowns.
package main
import (
"encoding/json"
"fmt"
"github.com/donnol/enum"
)
func main() {
items := []enum.Item[string]{
enum.ItemFrom("Fruit", "水果", "FRUIT"),
enum.ItemFrom("Vegetable", "蔬菜", "VEGETABLE"),
enum.ItemFrom("Apple", "苹果", "APPLE",
enum.WithExt[string](map[string]string{enum.ParentExtKey: "FRUIT"})),
enum.ItemFrom("Banana", "香蕉", "BANANA",
enum.WithExt[string](map[string]string{enum.ParentExtKey: "FRUIT"}),
enum.WithDisabled[string]()),
enum.ItemFrom("Carrot", "胡萝卜", "CARROT",
enum.WithExt[string](map[string]string{enum.ParentExtKey: "VEGETABLE"})),
}
tree := enum.BuildTree(items)
b, _ := json.MarshalIndent(tree, "", " ")
fmt.Println(string(b))
}
Output: [ { "key": "Fruit", "name": "水果", "value": "FRUIT", "children": [ { "key": "Apple", "name": "苹果", "value": "APPLE" }, { "key": "Banana", "name": "香蕉", "value": "BANANA", "disabled": true } ] }, { "key": "Vegetable", "name": "蔬菜", "value": "VEGETABLE", "children": [ { "key": "Carrot", "name": "胡萝卜", "value": "CARROT" } ] } ]
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
enumlint
command
Command enumlint is the CLI for the enumlint package.
|
Command enumlint is the CLI for the enumlint package. |
|
Package enumlint checks that enum values (created with enum.InitFor) are never written to after initialization.
|
Package enumlint checks that enum values (created with enum.InitFor) are never written to after initialization. |