Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

goenums

> 编程语言
Open source

Type Safe Enum generator for Go

374 stars0 likes1 views
WebsiteGitHub

About

Type Safe Enum generator for Go

goenums

goenums addresses Go's lack of native enum support by generating comprehensive, type-safe enum implementations from simple constant declarations. Transform basic iota based constants into feature-rich enums with string conversion, validation, JSON handling, database integration, and more.

Installation

go install github.com/zarldev/goenums@latest

Documentation

Documentation is available at https://zarldev.github.io/goenums.

For behavior changes and compatibility options in the upcoming v0.6 release, see the v0.6 migration guide.

Table of Contents

  • Migrating to v0.6
  • Usage
  • Features Expanded
    • Custom String Representations
      • Standard Name Comment
      • Name Comment with spaces
    • Extended Enum Types with Custom Fields
    • Case Insensitive String Parsing
    • JSON, Text, Binary, YAML, and Database Storage
      • Selecting generated interfaces
      • Selecting enum accessor style
      • Text marshaling compatibility
    • Numeric Parsing Support
    • Exhaustive Handling
    • Iterator Support (Go 1.23+)
    • Failfast Mode / Strict Mode
    • Legacy Mode
    • Verbose Mode
    • Constraints Mode
    • Output Format
    • Compile-time Validation
    • Compile-time Exhaustiveness
  • Getting Started
    • Basic Example
  • Requirements
  • Examples
  • License

Key Features

  • Type Safety: Wrapper types prevent accidental misuse of enum values
  • String Conversion: Automatic string representation and parsing
  • JSON Support: Built-in marshaling and unmarshaling
  • YAML Support: Built-in YAML marshaling and unmarshaling
  • Database Integration: SQL Scanner and Valuer implementations
  • Text/Binary Marshaling: Support for encoding.TextMarshaler/TextUnmarshaler and BinaryMarshaler/BinaryUnmarshaler
  • Numeric Parsing: Parse enums from various numeric types (int, float, etc.)
  • Validation: Methods to check for valid enum values
  • Iteration: Modern Go 1.23+ iteration support with legacy fallback
  • Extensibility: Add custom fields to enums via comments
  • Exhaustive Handling: Helper functions to ensure you handle all enum values
  • Alias Support: Alternative enum names via comment syntax
  • Accessor Style: Choose upper-case or idiomatic Go-style enum accessors via --accessor-style
  • Zero Dependencies: Completely dependency-free, using only the Go standard library

Usage

…

Features Expanded

Custom String Representations

Handle custom string representations defined in the comments of each enum. Support for enum strings with spaces is supported by adding the alternative name in double quotes:

Standard Name Comment

When the Alternative name does not contain spaces there is no need to add the double quotes.

go
type status int

//go:generate goenums -f -c status.go
const (
    unknown   status = iota // invalid UNKNOWN
    failed                  // FAILED
    passed                  // PASSED
    skipped                 // SKIPPED
    scheduled               // SCHEDULED
    running                 // RUNNING
    booked                  // BOOKED
)

Name Comment with spaces

When using Alternative names that contain spaces, the double quotes are required.

go
type order int

//go:generate goenums status.go
const (
	created     order = iota // "CREATED"
	approved                 // "APPROVED"
	processing               // "PROCESSING"
	readyToShip              // "READY TO SHIP"
	shipped                  // "SHIPPED TO CUSTOMER"
	delivered                // "DELIVERED TO CUSTOMER"
	cancelled                // "CANCELLED BY CUSTOMER"
	refunded                 // "REFUNDED TO CUSTOMER"
	closed                   // "CLOSED"
)

Extended Enum Types with Custom Fields

Add custom fields to your enums with type comments:

…

Then we can use the extended enum type:

go
earthWeight := 100.0
fmt.Printf("Weight on %s: %.2f kg\n", 
    solarsystem.Planets.MARS, 
    earthWeight * solarsystem.Planets.MARS.Gravity)

Case Insensitive String Parsing

Use the -i flag to enable case insensitive string parsing:

go
//go:generate goenums -i status.go

// Generated code will parse case insensitive strings. All
// of the below will validate and produce the 'PASSED' enum
status, err := validation.ParseStatus("PASSED")
if err != nil {
    fmt.Println("error:", err)
}
status, err := validation.ParseStatus("passed")
if err != nil {
    fmt.Println("error:", err)
}
status, err := validation.ParseStatus("Passed")
if err != nil {
    fmt.Println("error:", err)
}

JSON, Text, Binary, YAML, and Database Storage

The generated enum type also implements several common interfaces:

  • json.Marshaler and json.Unmarshaler
  • sql.Scanner and sql.Valuer
  • encoding.TextMarshaler and encoding.TextUnmarshaler
  • encoding.BinaryMarshaler and encoding.BinaryUnmarshaler

These interfaces are used to handle parsing for JSON, Text, Binary, and Database storage using the common standard library packages. As there is no standard library support for YAML, the generated YAML marshaling and unmarshaling methods are based on the * yaml.Marshaler and yaml.Unmarshaler interfaces from the goccy/go-yaml module.

Here is an example of the generated handling code:

…

Selecting generated interfaces

By default, goenums generates JSON, Text, YAML, SQL, and Binary interface methods. Use --interfaces to generate only specific interface implementations:

bash
goenums --interfaces=json,sql status.go

Valid values are json, text, yaml, sql, and binary. If the flag is omitted, all interfaces are generated.

-legacy-text only affects generated Text handlers. If text is not selected, -legacy-text has no generated-code effect.

Selecting enum accessor style

By default, goenums preserves the historical upper-case container accessor style:

go
Statuses.PENDING_APPROVAL

New projects that prefer idiomatic exported Go selectors can opt in to Go-style accessors:

bash
goenums --accessor-style=go status.go
go
Statuses.PendingApproval

Changing accessor style requires updating Go call sites, but it does not change enum aliases, parsing, serialized values, database values, or generated filenames.

Text marshaling compatibility

MarshalText now returns the raw enum text, which is the standard encoding.TextMarshaler behavior. If you need the pre-v0.6 quoted text output for compatibility, generate with -legacy-text:

bash
goenums -legacy-text status.go

JSON marshaling still emits valid JSON strings via json.Marshal, and UnmarshalJSON accepts both standard JSON strings and raw enum text for direct-call compatibility.

Numeric Parsing Support

The generated enums support parsing from various numeric types, matching the numeric input to the underlying enum constant value:

go
// Parse from different numeric types
status1, _ := validation.ParseStatus(1)        // int
status2, _ := validation.ParseStatus(int32(2)) // int32
status3, _ := validation.ParseStatus(3.0)      // float64
status4, _ := validation.ParseStatus(uint8(4)) // uint8

// All numeric types are supported: int, int8, int16, int32, int64,
// uint, uint8, uint16, uint32, uint64, float32, float64

The numeric parsing validates that:

  • Float values are whole numbers (no fractional part)
  • The numeric value corresponds to a defined underlying enum constant value, including offsets and gaps
  • Invalid enum constants and values outside the enum set are rejected

Exhaustive Handling

Ensure you handle all enum values with the generated Exhaustive function:

…

Iterator Support (Go 1.23+)

By default, goenums generates modern iterator support using Go 1.23's range-over-func feature:

go
// Using Go 1.23+ iterator
for status := range validation.Statuses.All() {
    fmt.Printf("Status: %s\n", status)
}

When using the legacy mode, the function is still called All() but it returns a slice of the enums.

go
// Legacy mode (or with -l flag)
for _, status := range validation.Statuses.All() {
    fmt.Printf("Status: %s\n", status)
}

Failfast Mode / Strict Mode

You can enable failfast mode by using the -failfast flag. This will cause the generator to fail on the first invalid enum it encounters while parsing. In failfast mode, the generated code includes a specific error variable and wrapped error returns:

go
//go:generate goenums -f status.go

// Generated code includes a specific error variable:
var ErrParseStatus = errors.New("invalid input provided to parse to Status")

// And returns wrapped errors for invalid values:
status, err := validation.ParseStatus("INVALID_STATUS")
if err != nil {
    // err will be: invalid input provided to parse to Status: invalid value INVALID_STATUS
    fmt.Println("error:", err)
    
    // You can check for the specific error type:
    if errors.Is(err, validation.ErrParseStatus) {
        fmt.Println("This is a Status parsing error")
    }
}

Legacy Mode

You can enable legacy mode by using the -legacy flag. This will generate code that is compatible with Go versions before 1.23.

Verbose Mode

You can enable verbose mode by using the -verbose flag. This will print out the generated code to the console.

Constraints Mode

Local numeric constraints are generated by default, so generated code has no external dependency. Use -x-exp-constraints only if you explicitly prefer importing golang.org/x/exp/constraints.

go
//go:generate goenums status.go

// Generated code will include local constraint definitions:
type float interface {
    float32 | float64
}
type integer interface {
    int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | uintptr
}
type number interface {
    integer | float
}

Output Format

You can specify the output format by using the -output flag. The default is go.

Compile-time Validation

The generated code includes compile-time validation to ensure enum values remain consistent. If you modify the underlying enum constants, the compiler will detect changes and prompt you to regenerate the enum code:

…

This ensures that if you change the order or values of your enum constants, you'll get a compile error reminding you to regenerate the enum code.

Compile-time Exhaustiveness

For true compile-time exhaustiveness checking, goenums generates a Matcher interface and Match/MustMatch functions. The interface has one method per valid enum value, so any type that implements it is guaranteed to handle every case:

…

The Match function returns an error if the matcher is nil or the enum value is not one of the valid generated cases. The MustMatch function panics instead. Both dispatch to the appropriate method on the matcher based on the enum value.

This is especially useful in tests to ensure all enum values are covered, and in production code where missing a case could cause subtle bugs. The compile-time check (var _ XMatcher = myMatcher{}) guarantees that the matcher type fully implements the generated interface before the code even compiles.

Getting Started

Basic Example

goenums is designed to work seamlessly with Go's standard tooling, particularly with `go:g

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Go

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言