enum

package module
v0.0.0-...-293c5c1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 19, 2018 License: MIT Imports: 4 Imported by: 0

README

go-enum

A struct based golang enum package that handles stringifying, marshalling, and unmarshalling.

Install

go get github.com/eddieowens/go-enum

Usage

Basic

The following creates an enum of currency codes and uses them on the Money struct

type CurrencyCodes struct {
    enum.Enum
    USD    enum.Const
    EUR    enum.Const
    CAD    enum.Const
    Custom enum.Const `enum:"CUSTOM"`
}

type Money struct {
    CurrencyCode CurrencyCode `json:"currency_code"`
    Amount       int          `json:"amount"`
}

To create a currency code you must use one of the following functions

// Instantiate with a provided value and panic if the value is not valid
cc := enum.MustConstruct(new(CurrencyCodes), enum.Const("USD")).(*CurrencyCodes)

// Instantiate with a provided value and return an error if the value is not valid
cc, err := enum.Construct(new(CurrencyCodes), enum.Const("USD")).(*CurrencyCodes)

// Create a new enum with no value set
cc := enum.New(new(CurrencyCodes)).(*CurrencyCodes)

To get the value and compare it with another

cc.Get() == cc.USD

To set the value, use any of the following

// If the value is invalid,  an error is returned
err := cc.Set(cc.CAD)

// If the value is invalid, a panic occurs
cc.MustSet(cc.CAD)

// Set the value to a `Const` type
cc.Set(Const("EUR"))
Complete example
func main() {
    // Create without a value
    cc := enum.New(new(CurrencyCodes)).(*CurrencyCodes)
    
    // Instantiate with a provided value then get it
    cc = enum.MustConstruct(new(CurrencyCodes), enum.Const("USD")).(*CurrencyCodes)
    fmt.Println(cc.USD == cc.Get()) // Prints true
    
    // Set valid value
    cc.MustSet(cc.Custom)
    
    // Set invalid value
    err := cc.Set(Const("Random"))
    fmt.Println(err.Error()) // Prints "Random is not a valid enum"
    
    // Get all possible enums
    consts := cc.GetAll()
    for _, c := range consts{
    	...
    }
    
    // Marshal
    m := Money{
        CurrencyCode: *cc,
        Amount: 5,
    }
    out, err := json.Marshal(c)
    fmt.Println(string(out)) // Prints "{"currency_code":"USD","amount":5}"
    
    // Unmarshal valid value
    var money Money

    json.Unmarshal([]byte("{\"currency_code\":\"USD\",\"amount\":5}"), &money)
    enum.Validate(&money.CurrencyCode) // <-- Must be run after unmarshal
    
    fmt.Println(money) // Prints "{USD 5}"
    
    // Unmarshal invalid value
    var money Money

    json.Unmarshal([]byte("{\"currency_code\":\"Random\",\"amount\":5}"), &money)
    err := enum.Validate(&money.CurrencyCode) // <-- Must be run after unmarshal
    
    fmt.Println(err.Error()) // Prints "Random is not a valid enum"
    
    // Stringify
    cc = enum.MustConstruct(new(CurrencyCodes), enum.Const("CUSTOM")).(*CurrencyCodes)
    fmt.Println(cc) // Prints "CUSTOM"
}

To note

Unmarshalling

All unmarshalling needs to be followed with a call to enum.Validate(...). If it is not the value placed on the enum may not be valid and the enum will not function as expected.

Const type

The name of the field on the struct will be the default value for the enum const. For example with CurrencyCodes.USD the Const value is "USD". In order to customize this value, add the tag enum:"<NAME>" like in CurrencyCodes.Custom

Docs

License

MIT

Documentation

Overview

A struct based golang enum package that handles stringifying, marshalling, and unmarshalling. All examples will be built from the following example types

type CurrencyCodes struct {
  enum.Enum
  USD    enum.Const
  Custom enum.Const `enum:"CUSTOM"`
}

type Money struct {
  CurrencyCode CurrencyCode `json:"currency_code"`
  Amount       int          `json:"amount"`
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Validate

func Validate(e Enummer) error

Instantiates the enum if that hasn't been done and validates that its current value is valid. Commonly used after unmarshalling an enum like so

func main() {
  var money Money

  json.Unmarshal([]byte("{\"currency_code\":\"USD\",\"amount\":5}"), &money)
  enum.Validate(&money.CurrencyCode) // <-- Must be run after unmarshal

  fmt.Println(money) // Prints "{USD 5}"
}

Types

type Const

type Const string

The base value for all Enum fields. The name of the field on the enum struct will be the default value for the enum const. For example The value of the USD const is "USD". In order to customize this value, add the tag enum:"<name>" for example

type CurrencyCodes struct {
  enum.Enum
  USD enum.Const `enum:"not usd"`
}

The value of the USD const is now "not usd"

type Enum

type Enum struct {
	// contains filtered or unexported fields
}

The base type for all Enums. Stores the current value and keeps track of all valid values.

func (*Enum) Get

func (e *Enum) Get() Const

Gets the value stored on the enum

func (*Enum) GetAll

func (e *Enum) GetAll() []Const

A list of all possible Consts on the enum

func (Enum) MarshalJSON

func (e Enum) MarshalJSON() ([]byte, error)

func (*Enum) MustSet

func (e *Enum) MustSet(s Const)

Set the value stored on the enum. Panics if the value is invalid

func (*Enum) Set

func (e *Enum) Set(c Const) error

Set the value stored on the enum. Returns an error if value is invalid

func (Enum) String

func (e Enum) String() string

func (*Enum) UnmarshalJSON

func (e *Enum) UnmarshalJSON(b []byte) error

Unmarshalls the string into an Enum. NOTE: you must run enum.Validate after unmarshalling a string like so

func main() {
  var money Money

  json.Unmarshal([]byte("{\"currency_code\":\"USD\",\"amount\":5}"), &money)
  enum.Validate(&money.CurrencyCode) // <-- Must be run after unmarshal

  fmt.Println(money) // Prints "{USD 5}"
}

type Enummer

type Enummer interface {
	Get() Const
	Set(c Const) error
	MustSet(c Const)
	GetAll() []Const
	// contains filtered or unexported methods
}

func Construct

func Construct(e Enummer, c Const) (Enummer, error)

Instantiates an Enum with the provided value. If the value is invalid, an error is returned otherwise, an Enummer is returned with a nil error

cc, err := enum.Construct(new(CurrencyCodes), enum.Const("USD"))
if err != nil {
  panic(err)
}
cc = cc.(*CurrencyCodes)

func MustConstruct

func MustConstruct(e Enummer, c Const) Enummer

Instantiates an Enum with the provided value. If the value is invalid, a panic occurs

cc := enum.MustConstruct(new(CurrencyCodes), enum.Const("USD")).(*CurrencyCodes)

func New

func New(e Enummer) Enummer

Creates a new Enummer with no value set

cc := enum.New(new(CurrencyCodes)).(*CurrencyCodes)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL