go-enum-encoding

go install github.com/nikolaydubina/go-enum-encoding@latest
[!WARNING]
v1.8.2
is the last version that supports go1.23 or bellow
- 200 LOC
- simple, fast, strict
- generates encoding/decoding, tests, benchmarks
type Color struct{ c uint8 }
//go:generate go-enum-encoding -type=Color
var (
UndefinedColor = Color{} // json:""
Red = Color{1} // json:"red"
Green = Color{2} // json:"green"
Blue = Color{3} // json:"blue"
)
It also works with raw iota
enums:
type Size uint8
//go:generate go-enum-encoding -type=Size
const (
UndefinedSize Size = iota // json:""
Small // json:"small"
Large // json:"large"
XLarge // json:"xlarge"
)
Generated benchmarks:
$ go test -bench=. -benchmem .
goos: darwin
goarch: arm64
pkg: github.com/nikolaydubina/go-enum-encoding/internal/testdata
cpu: Apple M3 Max
BenchmarkColor_UnmarshalText-16 752573839 1.374 ns/op 0 B/op 0 allocs/op
BenchmarkColor_AppendText-16 450123993 2.676 ns/op 0 B/op 0 allocs/op
BenchmarkColor_MarshalText-16 80059376 13.68 ns/op 8 B/op 1 allocs/op
BenchmarkImageSize_UnmarshalText-16 751743885 1.601 ns/op 0 B/op 0 allocs/op
BenchmarkImageSize_AppendText-16 500286883 2.402 ns/op 0 B/op 0 allocs/op
BenchmarkImageSize_MarshalText-16 81467318 16.46 ns/op 8 B/op 1 allocs/op
BenchmarkImageSize_String-16 856463289 1.330 ns/op 0 B/op 0 allocs/op
PASS
ok github.com/nikolaydubina/go-enum-encoding/internal/testdata 8.561s
References