pEnum

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2025 License: MIT Imports: 8 Imported by: 1

README

Go Version License

[📄 English Documentation](📄 中文文档 / Chinese Documentation)

Go Enum Utilities Library

pEnum provides a comprehensive implementation of enumeration types, supporting integer enums, string enums, and flag enums (bitwise enums). It offers rich enumeration operation methods to help developers use enum types more conveniently in Go projects.

🚀 Core Features

  1. Support for multiple enum types: integer enums, string enums, flag enums
  2. Automatic generation and numbering of enum values
  3. Validation and uniqueness checking of enum values
  4. Rich enum operation methods (bitwise operations, inclusion checks, etc.)
  5. Enum metadata query and management
  6. Concurrent-safe enum operations

📦 Installation

go get github.com/Xiao-yi123/pEnum

🎯 Quick Start

Basic Enum
import "github.com/Xiao-yi123/pEnum"

// Create basic enum
func main() {
    // Define enum values
    values := map[string]interface{}{
        "Red":   1,
        "Green": 2,
        "Blue":  3,
    }

    // Create enum metadata
    colorEnum := pEnum.NewEnum("Color", values)

    // Use enum
    red := colorEnum.Get("Red")
    fmt.Println(red.Name())  // Output: Red
    fmt.Println(red.Value()) // Output: 1
}
Integer Enum
// Create integer enum
func main() {
    values := map[string]interface{}{
        "Sunday":    0,
        "Monday":    1,
        "Tuesday":   2,
        "Wednesday": 3,
        "Thursday":  4,
        "Friday":    5,
        "Saturday":  6,
    }

    dayEnum := pEnum.NewIntEnum("Day", values)

    // Get integer enum value
    monday := dayEnum.Get("Monday").(pEnum.IntEnum)
    fmt.Println(monday.Int()) // Output: 1
}
Advanced Usage
Auto Numbering
// Using auto numbering feature
func main() {
    // nil value indicates using auto numbering
    values := map[string]interface{}{
        "Jan": nil,
        "Feb": nil,
        "Mar": nil,
        "Apr": nil,
    }

    // Auto numbering starting from 1
    monthEnum := pEnum.NewIntEnum("Month", values, pEnum.WithAutoNumber(1))

    jan := monthEnum.Get("Jan").(pEnum.IntEnum)
    fmt.Println(jan.Int()) // Output: 0

    feb := monthEnum.Get("Feb").(pEnum.IntEnum)
    fmt.Println(feb.Int()) // Output: 1
}
Enum Validation
func main() {
	UniqueEnum := pEnum.Unique(pEnum.NewEnum("Unique", map[string]interface{}{
		"FIRST":  1,
		"SECOND": 2,
		"THIRD":  2,
	}))
	// panic: duplicate values found: SECOND and THIRD both have value 2 [recovered]
	fmt.Println("Unique enum created successfully", UniqueEnum)
}

API Reference

Enum Types
  • Enum: Basic enum interface, implemented by all enum types
  • IntEnum: Integer enum interface, provides Int() method to get integer value
  • StrEnum: String enum interface, provides String() method to get string value
  • Flag: Flag enum interface, provides bitwise operation methods
Enum Creation Functions
  • NewEnum(name string, values map[string]interface{}, options ...EnumOption) EnumMeta: Create basic enum
  • NewIntEnum(name string, values map[string]interface{}, options ...EnumOption) EnumMeta: Create integer enum
  • NewStrEnum(name string, values map[string]interface{}, options ...EnumOption) EnumMeta: Create string enum
  • NewFlag(name string, values map[string]interface{}, options ...EnumOption) EnumMeta: Create flag enum
Enum Options
  • WithAutoNumber(start int) EnumOption: Set auto numbering start value
  • WithUnique() EnumOption: Ensure enum values are unique
  • WithOrdering() EnumOption: Sort enum members
  • WithBoundary(boundary *FlagBoundary) EnumOption: Set flag enum boundary
  • WithGenerateNextValue(fn) EnumOption: function for auto-generating values
  • WithMissing(fn) EnumOption: Set function for handling missing values
Enum Metadata Methods
  • Name() string: Get enum type name
  • Get(name string) Enum: Get enum member by name
  • GetByValue(value interface{}) (Enum, error): Get enum member by value
  • Members() []Enum: Get all enum members
  • ContainsValue(value interface{}) bool: Check if value exists
  • ContainsItem(name string) bool: Check if member exists
  • Len() int: Get enum member count
Flag Enum Methods
  • Contains(other Flag) bool: Check if specified flag is contained
  • And(other Flag) Flag: Bitwise AND operation
  • Or(other Flag) Flag: Bitwise OR operation
  • Xor(other Flag) Flag: Bitwise XOR operation
  • Invert() Flag: Bitwise NOT operation
  • Has(flag Flag) bool: Check if specified flag is contained (same functionality as Contains)

Notes

  1. Flag enum values must be powers of 2 to ensure correct bitwise operations
  2. When using auto numbering, enum members with nil values will be automatically assigned incrementing values值
  3. Enum operations are concurrent-safe, using internal read-write locks for protection
  4. Enum value uniqueness can be ensured using the WithUnique() option; duplicate values will cause a panic

Examples

For more usage examples, please refer to the enum_test.go file in the project.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// STRICT 严格模式:只允许预定义的标志值
	STRICT = &FlagBoundary{name: "STRICT", value: 0}
	// CONFORM 符合模式:允许符合位组合的值
	CONFORM = &FlagBoundary{name: "CONFORM", value: 1}
	// EJECT 弹出模式:自动移除无效的位
	EJECT = &FlagBoundary{name: "EJECT", value: 2}
	// KEEP 保持模式:保留所有位,即使无效
	KEEP = &FlagBoundary{name: "KEEP", value: 3}
)

常量定义 - 标志枚举的边界控制选项

Functions

func Auto

func Auto(value ...interface{}) interface{}

Auto 创建自动编号实例 该函数用于创建自动编号的枚举值 如果提供了参数,则直接返回该参数值 如果没有提供参数,则返回nil,表示需要自动生成值

参数:

  • value: 可选的枚举值

返回值:

  • interface{}: 枚举值或nil

func Member

func Member(value interface{}) *member

Member 创建强制成员值 用于标记某些值必须成为枚举成员

参数:

  • value: 要标记为强制成员的值

返回值:

  • *member: 强制成员值的指针

func Nonmember

func Nonmember(value interface{}) *nonmember

Nonmember 创建非成员值 用于标记某些值不应该成为枚举成员

参数:

  • value: 要标记为非成员的值

返回值:

  • *nonmember: 非成员值的指针

Types

type Enum

type Enum interface {
	// Name 返回枚举成员的名称
	Name() string

	// Value 返回枚举成员的值
	Value() interface{}

	// String 返回枚举成员的字符串表示
	String() string

	// Is 检查当前枚举是否与另一个枚举相等
	// 参数:
	//   - other: 要比较的另一个枚举
	// 返回值:
	//   - bool: 如果相等返回true,否则返回false
	Is(other Enum) bool

	// 嵌入JSON序列化接口
	json.Marshaler

	// 嵌入JSON反序列化接口
	json.Unmarshaler
}

Enum 枚举接口定义 所有枚举类型都必须实现此接口

type EnumMeta

type EnumMeta interface {
	// Name 返回枚举类型的名称
	Name() string

	// Get 根据枚举项的名称获取对应的枚举值
	// name: 枚举项的名称
	// 返回值: 对应的枚举值
	Get(name string) Enum

	// GetByValue 根据枚举值获取对应的枚举项
	// value: 枚举值
	// 返回值: 对应的枚举项和可能的错误
	GetByValue(value interface{}) (Enum, error)

	// Members 返回枚举类型的所有成员列表
	// 返回值: 包含所有枚举成员的切片
	Members() []Enum

	// String 返回枚举类型的字符串表示
	// 返回值: 枚举类型的字符串描述
	String() string

	// ContainsEnum 检查指定的枚举值是否存在于当前枚举类型中
	// value: 要检查的枚举值
	// 返回值: 如果存在返回true,否则返回false
	ContainsEnum(value Enum) bool

	// ContainsItem 检查指定名称的枚举项是否存在于当前枚举类型中
	// value: 要检查的枚举项名称
	// 返回值: 如果存在返回true,否则返回false
	ContainsItem(value string) bool

	// ContainsValue 检查指定值是否存在于当前枚举类型中
	// value: 要检查的值
	// 返回值: 如果存在返回true,否则返回false
	ContainsValue(value interface{}) bool

	// MembersMap 返回枚举类型的所有成员映射,键为枚举项名称,值为枚举值
	// 返回值: 包含所有枚举成员的映射
	MembersMap() map[string]Enum

	// GetItem 根据枚举项的名称获取对应的枚举值(与Get方法功能相同)
	// name: 枚举项的名称
	// 返回值: 对应的枚举值
	GetItem(name string) Enum

	// Len 返回枚举类型中成员的数量
	// 返回值: 枚举成员的数量
	Len() int

	// Iter 返回枚举类型的所有成员列表(与Members方法功能相同)
	// 返回值: 包含所有枚举成员的切片
	Iter() []Enum
	// contains filtered or unexported methods
}

EnumMeta 定义了枚举元数据的接口,提供了对枚举类型的各种操作方法

func EnumFactory

func EnumFactory(name string, enumValues map[string]interface{}, options ...EnumOption) EnumMeta

EnumFactory 枚举工厂函数 提供统一的枚举创建接口,支持各种选项配置

参数:

  • name: 枚举类型名称
  • enumValues: 枚举成员名称到值的映射
  • options: 枚举选项列表

返回值:

  • EnumMeta: 创建的枚举元数据

func NewEnum

func NewEnum(name string, enumValues map[string]interface{}, options ...EnumOption) EnumMeta

NewEnum 创建新的枚举类 该函数是枚举创建的核心函数,支持各种枚举类型的创建

参数:

  • name: 枚举类型的名称
  • enumValues: 枚举成员名称到值的映射
  • options: 枚举选项列表

返回值:

  • EnumMeta: 创建的枚举元数据

func NewFlag

func NewFlag(name string, enumValues map[string]interface{}, options ...EnumOption) EnumMeta

NewFlag 创建新的标志枚举类 该函数创建基于位运算的标志枚举,值必须是2的幂次

参数:

  • name: 标志枚举类型的名称
  • enumValues: 标志枚举成员名称到值的映射
  • options: 枚举选项列表

返回值:

  • EnumMeta: 创建的标志枚举元数据

func NewIntEnum

func NewIntEnum(name string, enumValues map[string]interface{}, options ...EnumOption) EnumMeta

NewIntEnum 创建新的整数枚举类 该函数创建只包含整数值的枚举类型

参数:

  • name: 枚举类型的名称
  • enumValues: 枚举成员名称到值的映射
  • options: 枚举选项列表

返回值:

  • EnumMeta: 创建的整数枚举元数据

func NewIntFlag

func NewIntFlag(name string, enumValues map[string]interface{}, options ...EnumOption) EnumMeta

NewIntFlag 创建新的整数标志枚举类 该函数创建基于位运算的整数标志枚举,边界设置为KEEP

参数:

  • name: 整数标志枚举类型的名称
  • enumValues: 整数标志枚举成员名称到值的映射
  • options: 枚举选项列表

返回值:

  • EnumMeta: 创建的整数标志枚举元数据

func NewStrEnum

func NewStrEnum(name string, enumValues map[string]interface{}, options ...EnumOption) EnumMeta

NewStrEnum 创建新的字符串枚举类 该函数创建只包含字符串值的枚举类型

参数:

  • name: 枚举类型的名称
  • enumValues: 枚举成员名称到值的映射
  • options: 枚举选项列表

返回值:

  • EnumMeta: 创建的字符串枚举元数据

func Unique

func Unique(meta EnumMeta) EnumMeta

Unique 装饰器 用于验证枚举值的唯一性,确保枚举中没有重复的值 该函数是 Verify 函数的便捷封装,只执行 UNIQUE 验证选项

参数:

  • meta: 要验证的枚举元数据

返回值:

  • EnumMeta: 验证通过的枚举元数据

func Verify

func Verify(meta EnumMeta, options ...VerifyOption) EnumMeta

Verify 验证装饰器,用于验证枚举是否满足指定的选项要求 该函数会对枚举进行一系列验证,如果验证失败会将 panic 转换为更友好的错误信息

参数:

  • meta: 要验证的枚举元数据
  • options: 验证选项列表,可以指定多个验证要求

返回值:

  • EnumMeta: 验证通过的枚举元数据

验证选项包括:

  • UNIQUE: 验证枚举值的唯一性
  • CONTINUOUS: 验证枚举值的连续性
  • NAMED_FLAGS: 验证标志枚举的命名规范

type EnumOption

type EnumOption func(*enumMeta)

EnumOption 枚举选项函数类型 用于配置枚举的创建选项

func WithAutoNumber

func WithAutoNumber(start int) EnumOption

WithAutoNumber 启用自动编号选项 该选项会为枚举成员自动分配连续的整数值

参数:

  • start: 起始编号值

返回值:

  • EnumOption: 枚举选项函数

func WithBoundary

func WithBoundary(boundary *FlagBoundary) EnumOption

WithBoundary 设置标志枚举的边界控制选项 用于控制标志枚举的行为边界

参数:

  • boundary: 边界控制选项

返回值:

  • EnumOption: 枚举选项函数

func WithGenerateNextValue

func WithGenerateNextValue(fn func(string, int, int, []interface{}) interface{}) EnumOption

WithGenerateNextValue 设置生成下一个值的函数 允许自定义枚举值的生成逻辑

参数:

  • fn: 生成下一个值的函数

返回值:

  • EnumOption: 枚举选项函数

func WithMissing

func WithMissing(fn func(interface{}) Enum) EnumOption

WithMissing 设置处理缺失值的函数 允许自定义处理不存在的枚举值的逻辑

参数:

  • fn: 处理缺失值的函数

返回值:

  • EnumOption: 枚举选项函数

func WithOrdering

func WithOrdering() EnumOption

WithOrdering 添加排序支持选项 该选项会根据枚举值对枚举成员进行排序

返回值:

  • EnumOption: 枚举选项函数

func WithUnique

func WithUnique() EnumOption

WithUnique 确保值唯一选项 该选项会验证枚举成员的值是否唯一,如果不唯一会引发panic

返回值:

  • EnumOption: 枚举选项函数

type Flag

type Flag interface {
	Enum
	// Contains 检查当前标志是否包含另一个标志的所有位
	// 参数:
	//   - other: 要检查的另一个标志
	// 返回值:
	//   - bool: 如果包含返回true,否则返回false
	Contains(other Flag) bool

	// And 执行按位与操作
	// 参数:
	//   - other: 与之进行按位与操作的标志
	// 返回值:
	//   - Flag: 按位与操作的结果
	And(other Flag) Flag

	// Or 执行按位或操作
	// 参数:
	//   - other: 与之进行按位或操作的标志
	// 返回值:
	//   - Flag: 按位或操作的结果
	Or(other Flag) Flag

	// Xor 执行按位异或操作
	// 参数:
	//   - other: 与之进行按位异或操作的标志
	// 返回值:
	//   - Flag: 按位异或操作的结果
	Xor(other Flag) Flag

	// Invert 执行按位取反操作
	// 返回值:
	//   - Flag: 按位取反操作的结果
	Invert() Flag

	// Has 检查是否包含某个标志(与Contains功能相同)
	// 参数:
	//   - flag: 要检查的标志
	// 返回值:
	//   - bool: 如果包含返回true,否则返回false
	Has(flag Flag) bool
}

Flag 标志枚举接口 扩展了基本枚举接口,添加了位运算相关的方法

type FlagBoundary

type FlagBoundary struct {
	// contains filtered or unexported fields
}

FlagBoundary 标志边界类型 用于控制标志枚举的行为边界

func (*FlagBoundary) String

func (f *FlagBoundary) String() string

String 返回 FlagBoundary 的字符串表示

type IntEnum

type IntEnum interface {
	Enum
	Int() int
}

IntEnum 整数枚举接口 扩展了基本枚举接口,添加了获取整数值的方法

type IntFlag

type IntFlag interface {
	Flag
	Int() int
}

IntFlag 整数标志枚举接口 扩展了标志枚举接口,添加了获取整数值的方法

type StrEnum

type StrEnum interface {
	Enum
	String() string
}

StrEnum 字符串枚举接口 扩展了基本枚举接口,添加了获取字符串值的方法

type VerifyOption

type VerifyOption int

VerifyOption 验证选项

const (
	CONTINUOUS VerifyOption = iota
	NAMED_FLAGS
	UNIQUE
)

Jump to

Keyboard shortcuts

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