goenum

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2025 License: MIT Imports: 1 Imported by: 0

README ยถ

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

goenum

Go enumeration generation and management toolkit with type safety and flexible naming patterns.


CHINESE README

ไธญๆ–‡่ฏดๆ˜Ž

Key Features

๐ŸŽฏ Smart Enum Generation: Auto generates type-safe enum code with customizable naming patterns
โšก Multiple Naming Modes: Supports prefix, suffix, middle, and single naming strategies
๐Ÿ”„ Type Safety: Compile-time enum validation with generic constraints
๐ŸŒ Flexible Types: Works with any comparable type (int, string, custom types)
๐Ÿ“‹ Validation Functions: Auto-generates Valid() and Check() methods for runtime validation

Installation

go get github.com/yyle88/goenum

Quick Start

1. Define Your Enum Configuration
package main

import (
    "github.com/yyle88/goenum/goenumgen"
)

func main() {
    // Configure enum generation
    config := &goenumgen.Config[string]{
        Type:       "StatusEnum",
        Name:       "Status", 
        BasicValue: "Status",
        DelimValue: "-",
        NamingMode: goenumgen.NamingMode.Suffix(), // "Status-OK", "Status-Error"
        IsGenValid: true,
        IsGenCheck: true,
        Options: []*goenumgen.EnumOption[string]{
            {Name: "OK", OptionValue: "OK"},
            {Name: "Error", OptionValue: "Error"}, 
            {Name: "Pending", OptionValue: "Pending"},
        },
    }
    
    // Generate enum code
    goenumgen.Generate(config, "internal/enums/status.go")
}
2. Generated Enum Code

The above configuration generates:

package enums

import "slices"

type StatusEnum string

const Status = StatusEnum("Status")

func (StatusEnum) OK() StatusEnum {
    return "Status" + "-" + "OK"
}

func (StatusEnum) Error() StatusEnum {
    return "Status" + "-" + "Error"
}

func (StatusEnum) Pending() StatusEnum {
    return "Status" + "-" + "Pending"
}

func (StatusEnum) Enums() []StatusEnum {
    return []StatusEnum{
        Status.OK(),
        Status.Error(), 
        Status.Pending(),
    }
}

func (value StatusEnum) Valid() bool {
    return slices.Contains(Status.Enums(), value)
}

func (value StatusEnum) Check() bool {
    return value == Status || slices.Contains(Status.Enums(), value)
}
3. Use Your Enums
package main

import (
    "fmt"
    "your-project/internal/enums"
    "github.com/yyle88/goenum"
)

func main() {
    // Create enum values
    status := enums.Status.OK()
    fmt.Println(status) // Output: Status-OK
    
    // Validate enum values
    if goenum.Valid(status) {
        fmt.Println("Valid enum value")
    }
    
    // Check with basic value support
    if goenum.Check(enums.Status) {
        fmt.Println("Basic value is valid")
    }
    
    // Get all enum values
    allStatuses := enums.Status.Enums()
    for _, s := range allStatuses {
        fmt.Printf("Status: %s, Valid: %t\n", s, s.Valid())
    }
}

Naming Modes

Prefix Mode

Pattern: option + delimiter + basic

NamingMode: goenumgen.NamingMode.Prefix()
// Result: "OK-Status", "Error-Status"
Suffix Mode

Pattern: basic + delimiter + option

NamingMode: goenumgen.NamingMode.Suffix()
// Result: "Status-OK", "Status-Error"
Middle Mode

Pattern: basic + option + delimiter

NamingMode: goenumgen.NamingMode.Middle()
// Result: "StatusOK-", "StatusError-"
Single Mode

Pattern: option

NamingMode: goenumgen.NamingMode.Single()
// Result: "OK", "Error"

Advanced Examples

HTTP Status Codes
config := &goenumgen.Config[int]{
    Type:       "HTTPStatusEnum",
    Name:       "HTTPStatus",
    BasicValue: 0,
    DelimValue: 0, // Not used for integers
    NamingMode: goenumgen.NamingMode.Single(),
    IsGenValid: true,
    IsGenCheck: true,
    Options: []*goenumgen.EnumOption[int]{
        {Name: "OK", OptionValue: 200},
        {Name: "NotFound", OptionValue: 404},
        {Name: "InternalError", OptionValue: 500},
    },
}
Database Connection States
config := &goenumgen.Config[string]{
    Type:       "ConnStateEnum", 
    Name:       "ConnState",
    BasicValue: "conn",
    DelimValue: ".",
    NamingMode: goenumgen.NamingMode.Prefix(),
    IsGenBasic: true,
    IsGenValid: true,
    Options: []*goenumgen.EnumOption[string]{
        {Name: "Connected", OptionValue: "active"},
        {Name: "Disconnected", OptionValue: "inactive"},
        {Name: "Connecting", OptionValue: "pending"},
    },
}
// Generates: "active.conn", "inactive.conn", "pending.conn"

Configuration Options

Field Type Description
Type string Generated enum type name
Name string Base constant name
BasicValue T Basic value for the enum
DelimValue T Delimiter for compound names
Options []*EnumOption[T] Enum option definitions
NamingMode NamingModeEnum Naming pattern strategy
IsGenBasic bool Generate Basic() method
IsGenValid bool Generate Valid() method
IsGenCheck bool Generate Check() method

Validation Functions

goenum.Valid()

Checks if a value exists in the enum set:

if goenum.Valid(status) {
    // Value is one of the defined enum options
}
goenum.Check()

Validates with basic value fallback:

if goenum.Check(status) {
    // Value is either basic value or valid enum option
}

Project Structure

goenum/
โ”œโ”€โ”€ goenum.go              # Main validation functions
โ”œโ”€โ”€ goenumgen/             # Code generation package
โ”‚   โ”œโ”€โ”€ generate.go        # Generation engine
โ”‚   โ””โ”€โ”€ naming_mode.go     # Naming pattern definitions
โ”œโ”€โ”€ internal/
โ”‚   โ”œโ”€โ”€ constraint/        # Generic type constraints
โ”‚   โ”œโ”€โ”€ utils/             # Utility functions
โ”‚   โ””โ”€โ”€ examples/          # Usage examples
โ”‚       โ”œโ”€โ”€ example1/      # Basic int enum
โ”‚       โ”œโ”€โ”€ example2/      # String enum with validation
โ”‚       โ”œโ”€โ”€ example3/      # Switch pattern enum
โ”‚       โ””โ”€โ”€ example4/      # Complex naming patterns
โ””โ”€โ”€ README.md

๐Ÿ“„ License

MIT License. See LICENSE.


๐Ÿค Contributing

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

  • ๐Ÿ› Found a bug? Open an issue on GitHub with reproduction steps
  • ๐Ÿ’ก Have a feature idea? Create an issue to discuss the suggestion
  • ๐Ÿ“– Documentation confusing? Report it so we can improve
  • ๐Ÿš€ Need new features? Share your use cases to help us understand requirements
  • โšก Performance issue? Help us optimize by reporting slow operations
  • ๐Ÿ”ง Configuration problem? Ask questions about complex setups
  • ๐Ÿ“ข Follow project progress? Watch the repo for new releases and features
  • ๐ŸŒŸ Success stories? Share how this package improved your workflow
  • ๐Ÿ’ฌ General feedback? All suggestions and comments are welcome

๐Ÿ”ง Development

New code contributions, follow this process:

  1. Fork: Fork the repo on GitHub (using the webpage interface).
  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 your changes with comprehensive tests
  6. Testing: (Golang project) Ensure tests pass (go test ./...) and follow Go code style conventions
  7. Documentation: Update documentation for user-facing changes and use meaningful commit messages
  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 pull 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 by submitting pull 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

Happy Coding with this package! ๐ŸŽ‰


GitHub Stars

Stargazers

Documentation ยถ

Overview ยถ

Package goenum: Go enumeration validation and type checking utilities Auto generates enum validation functions with type safety guarantees Supports generic enum types and provides compile-time enum verification Enables efficient enum validation with zero runtime allocations

goenum: Go ๆžšไธพ้ชŒ่ฏๅ’Œ็ฑปๅž‹ๆฃ€ๆŸฅๅทฅๅ…ทๅŒ… ่‡ชๅŠจ็”Ÿๆˆๅ…ทๆœ‰็ฑปๅž‹ๅฎ‰ๅ…จไฟ่ฏ็š„ๆžšไธพ้ชŒ่ฏๅ‡ฝๆ•ฐ ๆ”ฏๆŒๆณ›ๅž‹ๆžšไธพ็ฑปๅž‹๏ผŒๆไพ›็ผ–่ฏ‘ๆ—ถๆžšไธพ้ชŒ่ฏ ๅฎž็Žฐ้›ถ่ฟ่กŒๆ—ถๅˆ†้…็š„้ซ˜ๆ•ˆๆžšไธพ้ชŒ่ฏ

Index ยถ

Constants ยถ

This section is empty.

Variables ยถ

This section is empty.

Functions ยถ

func Check ยถ

func Check[E constraint.EnumItem[E]](value E) bool

Check validates enum value with basic value fallback support Accepts both basic enum values and valid enum options Combines basic value check with comprehensive enum validation

Check ้ชŒ่ฏๆžšไธพๅ€ผ๏ผŒๆ”ฏๆŒๅŸบๆœฌๅ€ผๅ›ž้€€ ๆŽฅๅ—ๅŸบๆœฌๆžšไธพๅ€ผๅ’Œๆœ‰ๆ•ˆ็š„ๆžšไธพ้€‰้กน ็ป“ๅˆๅŸบๆœฌๅ€ผๆฃ€ๆŸฅๅ’Œๅ…จ้ข็š„ๆžšไธพ้ชŒ่ฏ

func Valid ยถ

func Valid[E constraint.EnumType[E]](value E) bool

Valid checks if the given enum value exists in the enum set Uses compile-time type safety with generic constraints Returns true if value is found in the enum collection

Valid ๆฃ€ๆŸฅ็ป™ๅฎš็š„ๆžšไธพๅ€ผๆ˜ฏๅฆๅญ˜ๅœจไบŽๆžšไธพ้›†ๅˆไธญ ไฝฟ็”จๆณ›ๅž‹็บฆๆŸๅฎž็Žฐ็ผ–่ฏ‘ๆ—ถ็ฑปๅž‹ๅฎ‰ๅ…จ ๅฆ‚ๆžœๅ€ผๅœจๆžšไธพ้›†ๅˆไธญๆ‰พๅˆฐๅˆ™่ฟ”ๅ›ž true

Types ยถ

This section is empty.

Directories ยถ

Path Synopsis
Package goenumgen: Go enum code generation engine with flexible naming modes Auto generates type-safe enum code with customizable naming patterns Supports multiple output formats and validation function generation Provides compile-time safety with runtime efficiency optimization
Package goenumgen: Go enum code generation engine with flexible naming modes Auto generates type-safe enum code with customizable naming patterns Supports multiple output formats and validation function generation Provides compile-time safety with runtime efficiency optimization
internal
constraint
Package constraint: Generic type constraints for enum validation and type safety Defines interface contracts for enum types with compile-time guarantees Supports both basic enum validation and extended enum item functionality Enables type-safe enum operations with zero runtime overhead
Package constraint: Generic type constraints for enum validation and type safety Defines interface contracts for enum types with compile-time guarantees Supports both basic enum validation and extended enum item functionality Enables type-safe enum operations with zero runtime overhead

Jump to

Keyboard shortcuts

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