用于 Go 的安全枚举生成器
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.
go install github.com/zarldev/goenums@latestDocumentation 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.
--accessor-style…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:
When the Alternative name does not contain spaces there is no need to add the double quotes.
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
)When using Alternative names that contain spaces, the double quotes are required.
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"
)Add custom fields to your enums with type comments:
…Then we can use the extended enum type:
earthWeight := 100.0
fmt.Printf("Weight on %s: %.2f kg\n",
solarsystem.Planets.MARS,
earthWeight * solarsystem.Planets.MARS.Gravity)Use the -i flag to enable case insensitive string parsing:
//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)
}The generated enum type also implements several common interfaces:
json.Marshaler and json.Unmarshalersql.Scanner and sql.Valuerencoding.TextMarshaler and encoding.TextUnmarshalerencoding.BinaryMarshaler and encoding.BinaryUnmarshalerThese 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:
…By default, goenums generates JSON, Text, YAML, SQL, and Binary interface methods. Use --interfaces to generate only specific interface implementations:
goenums --interfaces=json,sql status.goValid 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.
By default, goenums preserves the historical upper-case container accessor style:
Statuses.PENDING_APPROVALNew projects that prefer idiomatic exported Go selectors can opt in to Go-style accessors:
goenums --accessor-style=go status.goStatuses.PendingApprovalChanging accessor style requires updating Go call sites, but it does not change enum aliases, parsing, serialized values, database values, or generated filenames.
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:
goenums -legacy-text status.goJSON marshaling still emits valid JSON strings via json.Marshal, and UnmarshalJSON accepts both standard JSON strings and raw enum text for direct-call compatibility.
The generated enums support parsing from various numeric types, matching the numeric input to the underlying enum constant value:
// 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, float64The numeric parsing validates that:
Ensure you handle all enum values with the generated Exhaustive function:
…By default, goenums generates modern iterator support using Go 1.23's range-over-func feature:
// 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.
// Legacy mode (or with -l flag)
for _, status := range validation.Statuses.All() {
fmt.Printf("Status: %s\n", status)
}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: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")
}
}You can enable legacy mode by using the -legacy flag. This will generate code that is compatible with Go versions before 1.23.
You can enable verbose mode by using the -verbose flag. This will print out the generated code to the console.
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: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
}You can specify the output format by using the -output flag. The default is go.
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.
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.
goenums is designed to work seamlessly with Go's standard tooling, particularly with `go:g
暂无开放 Issues,或尚未同步最近议题。