https://github.com/joelboim/gnum
True Enum for GO. Without code generation.
https://github.com/joelboim/gnum
enum enumeration go golang
Last synced: about 1 month ago
JSON representation
True Enum for GO. Without code generation.
- Host: GitHub
- URL: https://github.com/joelboim/gnum
- Owner: joelboim
- License: mit
- Created: 2022-11-16T17:20:40.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2024-10-22T13:42:06.000Z (over 1 year ago)
- Last Synced: 2025-08-09T21:39:02.690Z (6 months ago)
- Topics: enum, enumeration, go, golang
- Language: Go
- Homepage:
- Size: 330 KB
- Stars: 27
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://github.com/joelboim/gnum/tags)


[](https://pkg.go.dev/github.com/joelboim/gnum)
[](https://goreportcard.com/report/github.com/joelboim/gnum)


## Y Use gnum:grey_question:
* No code generation.
* Constant.
* Fast.
* Can be used as generic T.
* Concurrency safe.
## Benchmarks:dash:



## Getting Started
```bash
go get github.com/joelboim/gnum
````
# Example
First lets declare an enum type:
```go
package enums
import "github.com/joelboim/gnum"
type (
Color = gnum.Enum[struct {
Red,
Blue,
Green color
}]
color int
)
const (
Red Color = iota
Blue
Green
)
```
Now we can use it like other languages Enums:
```go
func main() {
fmt.Println(Red, Blue, Green) // Red Blue Green
fmt.Println(gnum.Names[Color]()) // [Red Blue Green]
fmt.Println(fmt.Sprintf("%T", gnum.Enums[Color]())) // []gnum.Enum[struct { Red main.color; Blue main.color; Green main.color }]
_, err := gnum.Parse[Color]("red")
fmt.Println(err) // error
colorJson, _ := json.Marshal(struct{ Color Color }{Blue})
fmt.Println(string(colorJson)) // {"Color":"Blue"}
}
```
Can be also used as generic type:
```go
func foo[T gnum.Enumer[T]](enum T) {
fmt.Println(
enum.Names(),
enum.Type())
}
func main() {
foo(Red) // [red blue green] color
foo(Square) // [Square] shape
}
```
If you need to customize elements of the enum you can do it with tags:
```go
type (
Color = gnum.Enum[struct {
Red color
Blue color `gnum:"value=3,name=b_l_u_e"`
Green color
Yellow color
}]
color int
)
```