enumx

package
v0.34.1 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package enumx 提供枚举管理能力。

定义枚举接口和注册表,支持类型安全的枚举管理。

用法:

type Status int

const (
    StatusActive   Status = 1
    StatusInactive Status = 2
)

func (s Status) Value() int    { return int(s) }
func (s Status) Label() string { return statusLabels[s] }
func (s Status) IsValid() bool { _, ok := statusLabels[s]; return ok }

var statusLabels = map[Status]string{
    StatusActive:   "启用",
    StatusInactive: "禁用",
}

var StatusRegistry = enumx.NewRegistry(StatusActive, StatusInactive)

// 使用
status := StatusRegistry.MustGet(1) // StatusActive
label := StatusRegistry.Label(1)    // "启用"

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Enum

type Enum interface {
	// Value 返回枚举的整数值。
	Value() int

	// Label 返回枚举的显示名称。
	Label() string

	// IsValid 检查枚举值是否有效。
	IsValid() bool
}

Enum 是枚举接口。

type Registry

type Registry[T Enum] struct {
	// contains filtered or unexported fields
}

Registry 是枚举注册表,提供类型安全的枚举管理。

func NewRegistry

func NewRegistry[T Enum](enums ...T) *Registry[T]

NewRegistry 创建枚举注册表。

**重复的 Value() 会 panic**:注册表是「value → 枚举」的映射,两个枚举同值时 「取到哪一个」取决于传入顺序——此前是**后者静默覆盖**(连 labels 一起覆盖) ⇒ 调用方拿到哪个枚举、看到哪个标签全看运气。枚举定义写错是编程错误, 构造期直接报出来。

func (*Registry[T]) All

func (r *Registry[T]) All() []T

All 获取所有已注册的枚举值(按 Value 升序排列)。

func (*Registry[T]) Get

func (r *Registry[T]) Get(value int) (T, bool)

Get 根据整数值获取枚举。

func (*Registry[T]) IsValid

func (r *Registry[T]) IsValid(value int) bool

IsValid 检查整数值是否是有效的枚举。

func (*Registry[T]) Label

func (r *Registry[T]) Label(value int) string

Label 获取枚举的显示名称;未登记的值返回 "unknown(<value>)"。

func (*Registry[T]) Len

func (r *Registry[T]) Len() int

Len 返回枚举数量。

func (*Registry[T]) Map

func (r *Registry[T]) Map() map[int]string

Map 返回 value→label 映射。

func (*Registry[T]) MustGet

func (r *Registry[T]) MustGet(value int) T

MustGet 根据整数值获取枚举,不存在时 panic。

func (*Registry[T]) Values

func (r *Registry[T]) Values() []int

Values 获取所有有效的枚举整数值(升序排列)。

Jump to

Keyboard shortcuts

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