GENUM - Go Enum Generator
Genum is a code generation tool for Go that automatically creates type-safe enum methods.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Features
- 🚀 Zero Boilerplate - Focus on your types, not repetitive code
- 🔒 Type Safety - Compile-time checked enum operations
- 🛠️ Flexible - Works with any base type (string, int, custom)
- 🔧 Go Generate Ready - Integrates seamlessly with your workflow
Install
go install github.com/sv3tluv/genum@latest
Usage
//go:generate genum -type=<Type>
Available flags:
-type string (required)
Specifies the enum type name to generate code for
-output string (optional)
Sets the output filename for generated code
If not provided, defaults to <source_filename>_genum.go
-trimprefix string (optional)
Removes the specified prefix from all enum value names
If not provided, uses the enum type name as the prefix
-case string (optional)
Controls case handling for string enum parsing
Available values: sensitive, ignore, lower, upper
If not provided, defaults to "sensitive"
- sensitive: case-sensitive matching (default)
- ignore: case-insensitive matching
- lower: converts input to lowercase before matching
- upper: converts input to uppercase before matching
enum.go:
package enum
//go:generate genum -type=Color
type Color string
const (
ColorRed Color = "red"
ColorBlack Color = "black"
ColorWhite Color = "white"
)
//go:generate genum -type=Status
type Status uint8
const (
Created Status = iota
Deleted
)
Run:
go generate ./...
enum_genum.go:
// Code generated by genum; DO NOT EDIT.
// Source: enum.go
package enum
import (
"fmt"
)
// === Color ===
var _defaultColor Color
func ParseColor(v string) (Color, error) {
value := Color(v)
if value.IsValid() {
return value, nil
}
return _defaultColor, fmt.Errorf("invalid Color: %v", v)
}
func (e Color) IsValid() bool {
switch e {
case
ColorRed,
ColorBlack,
ColorWhite:
return true
}
return false
}
func (e Color) Value() string {
return string(e)
}
func ColorValues() []Color {
return []Color{
ColorRed,
ColorBlack,
ColorWhite,
}
}
func ColorNames() []string {
return []string{
"Red",
"Black",
"White",
}
}
// === Status ===
var _defaultStatus Status
func ParseStatus(v uint8) (Status, error) {
value := Status(v)
if value.IsValid() {
return value, nil
}
return _defaultStatus, fmt.Errorf("invalid Status: %v", v)
}
func (e Status) IsValid() bool {
switch e {
case
Created,
Deleted:
return true
}
return false
}
func (e Status) Value() uint8 {
return uint8(e)
}
func StatusValues() []Status {
return []Status{
Created,
Deleted,
}
}
func StatusNames() []string {
return []string{
"Created",
"Deleted",
}
}