enum

package module
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2025 License: MIT Imports: 4 Imported by: 0

Image README

GitHub Workflow Status (branch) GoDoc Coverage Status Supported Go Versions GitHub Release Go Report Card

enum

Go native enum metadata management with generic type support and indexed collections.


CHINESE README

中文说明

Main Features

🎯 Type-Safe Enums: Generic enum descriptors binding custom metadata to Go native enums ⚡ Fast Lookup: O(1) indexed collections with code-based search 🔄 Flexible Metadata: Support custom metadata types beyond string descriptions 🌍 Default Handling: Configurable default values with chain-style configuration 📋 Validation Support: Built-in methods to check enum existence and active state

Installation

go get github.com/yyle88/enum

Usage

Basic Enum Collection
package main

import (
	"fmt"

	"github.com/yyle88/enum"
)

func main() {
	type Status string
	const (
		Unknown Status = "unknown"
		Success Status = "success"
		Failure Status = "failure"
	)

	// Create indexed collection without metadata
	enums := enum.NewEnums(
		enum.NewEnum(Unknown),
		enum.NewEnum(Success),
		enum.NewEnum(Failure),
	)

	// O(1) lookup using code
	if res, ok := enums.Lookup(Success); ok {
		fmt.Println(res.Code()) // Output: success
	}

	// Get with default fallback
	result := enums.Get(Status("not_exists"))
	fmt.Println(result.Code()) // Output: unknown (default)

	// List all codes
	fmt.Println(enums.List()) // Output: [unknown success failure]
}

⬆️ Source: Source

Enum Collection with Description
package main

import (
	"fmt"

	"github.com/yyle88/enum"
)

func main() {
	type Status string
	const (
		Unknown Status = "unknown"
		Success Status = "success"
		Failure Status = "failure"
	)

	// Create indexed collection with description
	enums := enum.NewEnums(
		enum.NewEnumWithDesc(Unknown, "Unknown Status"),
		enum.NewEnumWithDesc(Success, "Success Status"),
		enum.NewEnumWithDesc(Failure, "Failure Status"),
	)

	// O(1) lookup using code
	if res, ok := enums.Lookup(Success); ok {
		fmt.Println(res.Code())        // Output: success
		fmt.Println(res.Meta().Desc()) // Output: Success Status
	}

	// Get with default fallback
	result := enums.Get(Status("not_exists"))
	fmt.Println(result.Code())        // Output: unknown (default)
	fmt.Println(result.Meta().Desc()) // Output: Unknown Status
}

⬆️ Source: Source

Enum Collection with Custom Metadata
package main

import (
	"fmt"

	"github.com/yyle88/enum"
)

type MetaInfo struct {
	HTTPCode int
	Message  string
}

func main() {
	type Status string
	const (
		Unknown Status = "unknown"
		Success Status = "success"
		Failure Status = "failure"
	)

	// Create indexed collection with custom metadata
	enums := enum.NewEnums(
		enum.NewEnumWithMeta(Unknown, &MetaInfo{HTTPCode: 0, Message: "Unknown"}),
		enum.NewEnumWithMeta(Success, &MetaInfo{HTTPCode: 200, Message: "OK"}),
		enum.NewEnumWithMeta(Failure, &MetaInfo{HTTPCode: 500, Message: "Error"}),
	)

	// O(1) lookup using code
	if res, ok := enums.Lookup(Success); ok {
		fmt.Println(res.Code())          // Output: success
		fmt.Println(res.Meta().HTTPCode) // Output: 200
		fmt.Println(res.Meta().Message)  // Output: OK
	}

	// Get with default fallback
	result := enums.Get(Status("not_exists"))
	fmt.Println(result.Code())          // Output: unknown (default)
	fmt.Println(result.Meta().HTTPCode) // Output: 0
	fmt.Println(result.Meta().Message)  // Output: Unknown
}

⬆️ Source: Source

API Reference

Enum Creation
Function Description
NewEnum(code) Create enum without metadata
NewEnumWithDesc(code, desc) Create enum with string description
NewEnumWithMeta(code, meta) Create enum with custom metadata type
Enum Methods
Method Description
Code() Get the Go native enum value
Meta() Get the associated metadata
Collection Creation
Function Description
NewEnums(params...) Create indexed collection from enum instances
Collection Lookup
Method Description
Lookup(code) Find enum, returns (enum, exists)
Get(code) Find enum, returns default if not found
MustGet(code) Find enum, panics if not found
Collection Accessors
Method Description
List() Get slice of enum codes in defined sequence
ListValid() Get codes excluding default (unless marked valid)
Default Value Management
Method Description
GetDefault() Get default enum instance
GetDefaultCode() Get default enum code value
SetDefault(enum) Set default enum instance
SetDefaultCode(code) Set default using code value
SetDefaultValid(valid) Mark default as valid in Valid()
UnsetDefault() Remove default value
Chain-Style Configuration
Method Description
WithDefault(enum) Set default and return collection
WithDefaultCode(code) Set default using code and return collection
WithDefaultValid(valid) Set valid state and return collection
WithUnsetDefault() Remove default and return collection

📄 License

MIT License - see LICENSE.


💬 Contact & Feedback

Contributions are welcome! Report bugs, suggest features, and contribute code:

  • 🐛 Mistake reports? Open an issue on GitHub with reproduction steps
  • 💡 Fresh ideas? Create an issue to discuss
  • 📖 Documentation confusing? Report it so we can improve
  • 🚀 Need new features? Share the use cases to help us understand requirements
  • Performance issue? Help us optimize through reporting slow operations
  • 🔧 Configuration problem? Ask questions about complex setups
  • 📢 Follow project progress? Watch the repo to get new releases and features
  • 🌟 Success stories? Share how this package improved the workflow
  • 💬 Feedback? We welcome suggestions and comments

🔧 Development

New code contributions, follow this process:

  1. Fork: Fork the repo on GitHub (using the webpage UI).
  2. Clone: Clone the forked project (git clone https://github.com/yourname/repo-name.git).
  3. Navigate: Navigate to the cloned project (cd repo-name)
  4. Branch: Create a feature branch (git checkout -b feature/xxx).
  5. Code: Implement the changes with comprehensive tests
  6. Testing: (Golang project) Ensure tests pass (go test ./...) and follow Go code style conventions
  7. Documentation: Update documentation to support client-facing changes
  8. Stage: Stage changes (git add .)
  9. Commit: Commit changes (git commit -m "Add feature xxx") ensuring backward compatible code
  10. Push: Push to the branch (git push origin feature/xxx).
  11. PR: Open a merge request on GitHub (on the GitHub webpage) with detailed description.

Please ensure tests pass and include relevant documentation updates.


🌟 Support

Welcome to contribute to this project via submitting merge requests and reporting issues.

Project Support:

  • Give GitHub stars if this project helps you
  • 🤝 Share with teammates and (golang) programming friends
  • 📝 Write tech blogs about development tools and workflows - we provide content writing support
  • 🌟 Join the ecosystem - committed to supporting open source and the (golang) development scene

Have Fun Coding with this package! 🎉🎉🎉


GitHub Stars

Stargazers

Image Documentation

Overview

Package enum: Utilities to manage Go native enum with custom metadata Provides type-safe enum descriptors with metadata binding Supports two generics: enumCode and metaType

enum: Go 原生枚举元数据管理工具 提供带元数据绑定的类型安全枚举描述符 支持双泛型:enumCode 和 metaType

Package enum: Collection management to handle Go native enum metadata Provides indexed collections of enum descriptors with lookup methods Enables fast lookup using code value with efficient enum handling

enum: Go 原生枚举元数据集合管理 提供带有查找方法的枚举描述符索引集合 支持按 code 枚举值快速检索,实现高效枚举处理

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Enum

type Enum[enumCode comparable, metaType any] struct {
	// contains filtered or unexported fields
}

Enum wraps a Go native enum with custom metadata Associates custom metadata with the enum value via Meta() method Uses two generics to maintain type checking across enum and metadata

Enum 使用自定义元数据包装 Go 原生枚举 通过 Meta() 方法关联枚举值与自定义元数据 使用双泛型在枚举和元数据类型间保持类型安全

func NewEnum

func NewEnum[enumCode comparable](code enumCode) *Enum[enumCode, *MetaNone]

NewEnum creates a new Enum instance with Go native enum Use this when you just need enum mapping without description Returns a reference to the created Enum instance

创建新的 Enum 实例,绑定 Go 原生枚举 当只需要枚举映射而不需要描述时使用此函数 返回创建的 Enum 实例指针

func NewEnumWithDesc

func NewEnumWithDesc[enumCode comparable](code enumCode, description string) *Enum[enumCode, *MetaDesc]

NewEnumWithDesc creates a new Enum instance with Go native enum and description Use this when you need both enum mapping and human-readable description The description param provides custom description used in docs and UI

创建带有 Go 原生枚举和描述的新 Enum 实例 当需要枚举映射和人类可读描述时使用此函数 description 参数提供用于文档和显示的自定义描述

func NewEnumWithMeta

func NewEnumWithMeta[enumCode comparable, metaType any](code enumCode, meta metaType) *Enum[enumCode, metaType]

NewEnumWithMeta creates a new Enum instance with Go native enum and custom metadata Use this when you need customized metadata types beyond simple string description The meta param accepts custom metadata types (e.g. i18n descriptions)

创建带有 Go 原生枚举和自定义元数据的新 Enum 实例 当需要超越简单字符串描述的灵活元数据类型时使用此函数 meta 参数接受任意自定义元数据类型(如双语描述)

func (*Enum[enumCode, metaType]) Code

func (e *Enum[enumCode, metaType]) Code() enumCode

Code returns the Go native enum value Provides access to the source enum value

返回 Go 原生枚举值 提供对源枚举值的访问

func (*Enum[enumCode, metaType]) Meta

func (e *Enum[enumCode, metaType]) Meta() metaType

Meta returns the metadata associated with this enum Provides access to custom metadata like description via MetaDesc

返回与此枚举关联的元数据 提供对自定义元数据(如通过 MetaDesc 获取描述)的访问

type Enums

type Enums[C comparable, M any] struct {
	// contains filtered or unexported fields
}

Enums manages a collection of Enum instances with indexed lookups Maintains map enabling efficient lookup using code value Provides O(1) lookup when searching code value Includes a configurable default value returned when lookups miss

Enums 管理 Enum 实例集合并提供索引查找 维护映射表以通过 code 值高效检索 为 code 枚举值搜索提供 O(1) 查找 支持在查找失败时返回可选的默认值

func NewEnums

func NewEnums[C comparable, M any](params ...*Enum[C, M]) *Enums[C, M]

NewEnums creates a new Enums collection from the given Enum instances Builds indexed map enabling efficient lookup using code value The first item becomes the default value if provided Returns a reference to the created Enums collection

从给定的 Enum 实例创建新的 Enums 集合 构建索引映射以通过 code 值高效查找 如果提供了参数,第一个项成为默认值 返回创建的 Enums 集合指针

func (*Enums[C, M]) Get

func (c *Enums[C, M]) Get(code C) *Enum[C, M]

Get finds an Enum using its code value Returns default value if no enum with the given code exists Panics if no default value has been configured

通过 code 值检索 Enum 如果不存在具有给定 code 的枚举则返回默认值 如果未配置默认值则会 panic

func (*Enums[C, M]) GetDefault

func (c *Enums[C, M]) GetDefault() *Enum[C, M]

GetDefault returns the current default Enum value Panics if no default value has been configured

返回当前的默认 Enum 值 如果未配置默认值则会 panic

func (*Enums[C, M]) GetDefaultCode

func (c *Enums[C, M]) GetDefaultCode() C

GetDefaultCode returns the code value of the default Enum Panics if no default value has been configured

返回默认 Enum 的 code 值 如果未配置默认值则会 panic

func (*Enums[C, M]) List

func (c *Enums[C, M]) List() []C

List returns a slice containing each code value in the defined sequence Maintains the same sequence as enum values were registered

返回一个包含各 code 值的切片,次序与定义时一致 保持枚举值注册时的顺序

func (*Enums[C, M]) ListValid

func (c *Enums[C, M]) ListValid() []C

ListValid returns a slice excluding the default code value If no default value is configured, returns each code value

返回一个切片,排除默认 code 值,其余按定义次序排列 如果未配置默认值,则返回所有 code 值

func (*Enums[C, M]) Lookup

func (c *Enums[C, M]) Lookup(code C) (*Enum[C, M], bool)

Lookup finds an Enum using its code value Returns the Enum and true if found, nil and false otherwise Use this when you need to check existence before accessing the value

通过 code 值查找 Enum 找到时返回 Enum 和 true,否则返回 nil 和 false 当需要在访问值之前检查是否存在时使用此方法

func (*Enums[C, M]) MustGet

func (c *Enums[C, M]) MustGet(code C) *Enum[C, M]

MustGet finds an Enum using its code value Panics if no enum with the given code exists

通过 code 值检索 Enum 如果不存在具有给定 code 的枚举则会 panic

func (*Enums[C, M]) SetDefault

func (c *Enums[C, M]) SetDefault(enum *Enum[C, M])

SetDefault sets the default Enum value to return when lookups miss Allows dynamic configuration of the fallback value post creation Panics if defaultEnum is nil, use UnsetDefault to remove the default value

设置查找失败时返回的默认 Enum 值 允许在创建后动态配置回退值 如果 defaultEnum 为 nil 则会 panic,使用 UnsetDefault 清除默认值

func (*Enums[C, M]) SetDefaultCode

func (c *Enums[C, M]) SetDefaultCode(code C)

SetDefaultCode sets the default using a code value Panics if the specified code is not found in the collection

使用 code 值设置默认值 如果指定的 code 不存在则会 panic

func (*Enums[C, M]) SetDefaultValid

func (c *Enums[C, M]) SetDefaultValid(valid bool)

SetDefaultValid marks the default value as active when true When active, Valid() includes the default Panics if no default value exists, panics if defaultValid has been set

标记默认值是否应被视为有效 当 valid 为 true 时,Valid() 包含默认值 如果无默认值或 defaultValid 已设置则会 panic

func (*Enums[C, M]) UnsetDefault

func (c *Enums[C, M]) UnsetDefault()

UnsetDefault unsets the default Enum value Once invoked, Get() lookups panic if not found Panics if no default value exists at the moment

取消设置默认 Enum 值 调用此方法后,Get() 查找失败时会 panic 如果当前无默认值则会 panic

func (*Enums[C, M]) WithDefault

func (c *Enums[C, M]) WithDefault(enum *Enum[C, M]) *Enums[C, M]

WithDefault sets the default Enum value and returns the Enums instance Enables fluent chain-style configuration during initialization Convenient when setting defaults in package-scope variable declarations

设置默认 Enum 值并返回 Enums 实例 支持初始化时的流式链式配置 适用于在全局变量声明中设置默认值

func (*Enums[C, M]) WithDefaultCode

func (c *Enums[C, M]) WithDefaultCode(code C) *Enums[C, M]

WithDefaultCode sets the default using a code value and returns the Enums instance Convenient chain method when you know the default code value Panics if the specified code is not found in the collection

使用 code 值设置默认值并返回 Enums 实例 当你知道默认 code 值时的便捷链式方法 如果指定的 code 不存在则会 panic

func (*Enums[C, M]) WithDefaultValid

func (c *Enums[C, M]) WithDefaultValid(valid bool) *Enums[C, M]

WithDefaultValid marks the default as active and returns the Enums instance When active, Valid() includes the default Convenient chain method to configure default active state at initialization

标记默认值为有效并返回 Enums 实例 当 valid 为 true 时,Valid() 包含默认值 用于初始化时配置默认值有效性的便捷链式方法

func (*Enums[C, M]) WithUnsetDefault

func (c *Enums[C, M]) WithUnsetDefault() *Enums[C, M]

WithUnsetDefault unsets the default Enum value and returns the Enums instance Enables fluent chain-style configuration to remove default value Once invoked, Get() lookups panic if not found

取消设置默认 Enum 值并返回 Enums 实例 支持流式链式配置以移除默认值 之后 Get() 查找失败时会 panic

type MetaDesc

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

MetaDesc represents metadata with string description attached to enums

MetaDesc 代表带字符串描述的枚举元数据

func (*MetaDesc) Desc

func (c *MetaDesc) Desc() string

Desc returns the custom description of the enum Provides human-readable description with documentation purposes

返回枚举的自定义描述 提供人类可读的描述用于文档目的

type MetaNone

type MetaNone struct{}

MetaNone represents blank metadata when enums have no description

MetaNone 代表无描述枚举的空元数据

Image Directories

Path Synopsis
internal
demos/demo1x command
demos/demo2x command
demos/demo3x command
Package utils: Private utilities handling pointers and zero values Provides generic functions to handle pointers and value extraction
Package utils: Private utilities handling pointers and zero values Provides generic functions to handle pointers and value extraction

Jump to

Keyboard shortcuts

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