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 ¶
- type Enum
- type Registry
- func (r *Registry[T]) All() []T
- func (r *Registry[T]) Get(value int) (T, bool)
- func (r *Registry[T]) IsValid(value int) bool
- func (r *Registry[T]) Label(value int) string
- func (r *Registry[T]) Len() int
- func (r *Registry[T]) Map() map[int]string
- func (r *Registry[T]) MustGet(value int) T
- func (r *Registry[T]) Values() []int
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 ¶
NewRegistry 创建枚举注册表。
**重复的 Value() 会 panic**:注册表是「value → 枚举」的映射,两个枚举同值时 「取到哪一个」取决于传入顺序——此前是**后者静默覆盖**(连 labels 一起覆盖) ⇒ 调用方拿到哪个枚举、看到哪个标签全看运气。枚举定义写错是编程错误, 构造期直接报出来。
Click to show internal directories.
Click to hide internal directories.