GithubHelp home page GithubHelp logo

orsinium-labs / enum Goto Github PK

View Code? Open in Web Editor NEW
424.0 5.0 20.0 36 KB

Type safe enums for Go without code generation or reflection

Home Page: https://pkg.go.dev/github.com/orsinium-labs/enum

License: MIT License

Go 100.00%
enum enum-to-string enums generics go golang metaprogramming reflection string-to-enum

enum's Introduction

enum

[ 📄 docs ] [ 🐙 github ] [ ❤️ sponsor ]

Type safe enums for Go without code generation or reflection.

😎 Features:

  • Type-safe, thanks to generics.
  • No code generation.
  • No reflection.
  • Well-documented, with working examples for every function.
  • Flexible, supports both static and runtime definitions.
  • Zero-dependency.

📦 Installation

go get github.com/orsinium-labs/enum

🛠️ Usage

Define:

type Color enum.Member[string]

var (
  Red    = Color{"red"}
  Green  = Color{"green"}
  Blue   = Color{"blue"}
  Colors = enum.New(Red, Green, Blue)
)

Parse a raw value (nil is returned for invalid value):

parsed := Colors.Parse("red")

Compare enum members:

parsed == Red
Red != Green

Accept enum members as function arguments:

func SetPixel(x, i int, c Color)

Loop over all enum members:

for _, color := range Colors.Members() {
  // ...
}

Ensure that the enum member belongs to an enum (can be useful for defensive programming to ensure that the caller doesn't construct an enum member manually):

func f(color Color) {
  if !colors.Contains(color) {
    panic("invalid color")
  }
  // ...
}

Define custom methods on enum members:

func (c Color) UnmarshalJSON(b []byte) error {
  return nil
}

Dynamically create enums to pass multiple members in a function:

func SetPixel2(x, y int, colors enum.Enum[Color, string]) {
  if colors.Contains(Red) {
    // ...
  }
}

purple := enum.New(Red, Blue)
SetPixel2(0, 0, purple)

Enum members can be any comparable type, not just strings:

type ColorValue struct {
  UI string
  DB int
}
type Color enum.Member[ColorValue]
var (
  Red    = Color{ColorValue{"red", 1}}
  Green  = Color{ColorValue{"green", 2}}
  Blue   = Color{ColorValue{"blue", 3}}
  Colors = enum.New(Red, Green, Blue)
)

fmt.Println(Red.Value.UI)

If the enum has lots of members and new ones may be added over time, it's easy to forget to register all members in the enum. To prevent this, use enum.Builder to define an enum:

type Color enum.Member[string]

var (
  b      = enum.NewBuilder[string, Color]()
  Red    = b.Add(Color{"red"})
  Green  = b.Add(Color{"green"})
  Blue   = b.Add(Color{"blue"})
  Colors = b.Enum()
)

🤔 QnA

  1. What happens when enums are added in Go itself? I'll keep it alive until someone uses it but I expect the project popularity to quickly die out when there is native language support for enums. When you can mess with the compiler itself, you can do more. For example, this package can't provide an exhaustiveness check for switch statements using enums (maybe only by implementing a linter) but proper language-level enums would most likely have it.
  2. Is it reliable? Yes, pretty much. It has good tests but most importantly it's a small project with just a bit of the actual code that is hard to mess up.
  3. Is it maintained? The project is pretty much feature-complete, so there is nothing for me to commit and release daily. However, I accept contributions (see below).
  4. What if I found a bug? Fork the project, fix the bug, write some tests, and open a Pull Request. I usually merge and release any contributions within a day.

enum's People

Contributors

orsinium avatar xyproto avatar lukeshu avatar iwata avatar euanwm avatar

Stargazers

Luke Barratt avatar wenxinxiang avatar kokoro avatar Dave avatar Eric Francis avatar Alexey Shevchenko avatar Sergio Kovtunenko avatar Angel avatar Bjoern Weidlich avatar Kapil Agrawal avatar Jungwoon avatar  avatar Mehmet Ali Mergen avatar Herman Slatman avatar Ron Evans avatar Gabriel Francisco avatar Aaron Shumway avatar Chaim-David Gazda avatar Chili avatar Stephan avatar  avatar Japorized avatar  avatar  avatar Fanny Arif Nasrudin avatar Taras Woronjanski avatar Jongwon Youn avatar Andreas Motl avatar jxwu avatar Vincent Free avatar Rodrigo Villablanca avatar  avatar Tawan Saeheng avatar cieons avatar fghwett avatar Luke Frisken avatar ccoVeille avatar Benjamin Long avatar  avatar Kyrylo Baibula avatar  avatar Dmitry Starov avatar James Lucktaylor avatar Nikita Zhenev avatar Song Lim avatar FuXiang Shu avatar Chang avatar Cristian Garrido avatar Gleb Haranin avatar Jonas Rothmann avatar ndrslmpk avatar Dami Izolan avatar Maksim Martianov avatar  avatar Fernando Silva avatar angelside avatar Sumit Kumar avatar flamendless avatar Kenny Chen avatar Igor Polyakov avatar Will Irmler avatar Gál Tamás avatar  avatar  avatar tsingson avatar ik5 avatar John Bannister avatar Ashish avatar Milos Gajdos avatar Nikolay Dubina avatar Adam Zell avatar Dino Angelov avatar Brawl avatar  avatar Rohit Jha avatar Gonzalo Peci avatar Sam avatar  avatar  avatar Christian Kihm-Landau avatar  avatar Kyriakos Akriotis avatar WL avatar Anton Ilyushenkov avatar Jujo avatar Prof Syd Xu avatar Daniel Lewan avatar Scott Leggett avatar Jimmie Han avatar Alec Thomas avatar Filip Sushko avatar  avatar  avatar  avatar Cleyan Sampaio avatar Serhii Mudryk avatar  avatar Piotr Bocheński avatar Liao avatar HK avatar

Watchers

Scott Leggett avatar ccoVeille avatar Nuno Lopes avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.