enumgen is a type-safe enum generator for Go. It generates robust, type-safe wrappers around string constants, providing validation, string conversion, and helper methods.
- Type Safety: Generates custom types for enums to prevent accidental misuse.
- Validation: Includes an
IsValid()method to check if a value is a valid enum member. - String Support: Implements the
fmt.Stringerinterface. - Parsing: Provides a
FromString()method to safely convert strings to enum types. - Auto-testing: Automatically generates unit tests for the generated enums.
- Easy Integration: Designed to work seamlessly with
go generate.
go install github.com/dekey/enums/cmd/enumgen@latest- Define your constants in a Go file.
- Add the
//go:generate enumgen --name=<Name>directive above theconstblock.
In internal/examples/enums/contract.go:
package enums
//go:generate enumgen --name=Role
const (
admin = "admin"
editor = "editor"
viewer = "viewer"
)Run the generator:
go generate ./...The generator will create enum_role_gen.go with the following API:
type RoleType string
var RoleTypes struct {
Admin() RoleType
Editor() RoleType
Viewer() RoleType
FromString(string) (RoleType, error)
}
func (e RoleType) IsValid() bool
func (e RoleType) String() stringThe project includes a Makefile for common tasks:
make build: Build theenumgenbinary.make test: Run tests.make lint: Run the linter.make format: Format the code.
MIT (See LICENSE)