Skip to content

yyle88/enum

Repository files navigation

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

About

Go native enums Generic type offers enum collections with simple code

Resources

License

Stars

Watchers

Forks

Packages

No packages published