Skip to content

Repository files navigation

go-enumerator

go-enumerator is a tool for generating compile-time safe enumerations in Go. It follows the sealed interface pattern to forbid value manipulation outside the package.

1. Goals

Project main goal is to deliver a simple, easy-to-use, reliable tool for generating compile-time safe enumerations in Go.

2. Non-goals

  • Provide true Algebraic Data Type enumeration implementation.

  • Support multiple usage contexts (e.g. XML marshalling, database storage).

3. Installation

Use standard go install command to install go-enumerator executable:

go install github.com/tompaz3/go-enumerator

This will install the go-enumerator executable in your $GOPATH/bin directory.

4. Usage

go-enumerator generates Go compile-time safe enumerations. It is encouraged to create enums in their own, separate packages to forbid value manipulation.

To generate the enum use the go-enumerator binary directly or through //go:generate directive.

Generate using go-enumerator binary:

# generate Color enum with Undefined,Red,Green,Blue values
# with JSON marshalling support, undefined value
# and deserialize unknown values to Undefined
go-enumerator -destination ./color/color.go -package color -type Color -values Undefined,Red,Green,Blue -undefined Undefined -marshal-json -unmarshal-json-to-undefined --copyright ../../LICENSE

Generate using //go:generate directive:

// generate Color enum with Undefined,Red,Green,Blue values
// with JSON marshalling support, undefined value
// and deserialize unknown values to Undefined

//go:generate go-enumerator -destination ./color/color.go -package color -type Color -values Undefined,Red,Green,Blue -undefined Undefined -marshal-json -unmarshal-json-to-undefined --copyright ../../LICENSE

4.1. Arguments

go-enumerator supports the following arguments:

Table 1. Arguments
Argument Default value Description Examples

destination

""

Optional: Destination file path. os.Stdout if empty

-destination ./color/color.go

package

""

Required: Package name

-package color

type

""

Required: Enum type name

-type Color

values

""

Required: Enum values separated by comma

-values Undefined,Red,Green,Blue

undefined

""

Optional: Enum undefined value (used for OfOrUndefined method). Must be one of the values provided as values parameter.

-undefined Undefined

marshal-json

false

Optional: Generate JSON marshalling methods

-marshal-json

unmarshal-json-to-undefined

false

Optional: Deserialize unknown values to undefined value

-unmarshal-json-to-undefined

copyright

""

Optional: Copyright notice to be included in the generated file

-copyright ../../LICENSE

go-check-sumtype

false

Optional: Add //sumtype:decl directive comment for generated sum type, recognized by go-check-sumtype linter for exhaustiveness checks

-go-check-sumtype

version

false

Optional: Print version. Will ignore all the other flags and simply print the executable version.

-version

4.2. Example generated enum

color.go file is the example generated file - using the //go:generate command as specified above (Generate using go:generate directive).

4.2.1. Generated file structure

The generated file will consist of:

  • Copyright notice (if copyright parameter specified)

  • Package declaration

  • Enum interface definition with the type name, sealedType() (sealed function), String() string and ToJSONMarshallable() MarshallableType functions (see MarshallableType) for details.

  • Base struct implementation

    • Global variable declarations with enum values

    • String() string function

    • Values() []Type function

    • Of(name string) (Type, bool) function implementation for mapping the enum based on the string value

    • OfOrUndefined(name string) Type function implementation for mapping the enum based on the string value, returning undefined if the value is not found - only if undefined parameter is specified

    • ToJSONMarshallable() MarshallableType function to change this enum to JSON marshallable type - only if marshal-json parameter is specified

  • MarshallableType type for JSON marshalling. Separate type is used as json.Unmarshaler requires pointer receiver. If you ever want to use the enum in a struct that implements json.Marshaler or json.Unmarshaler, use the related MarshallableType type.

    • MarshalJSON() ([]byte, error) function implementation for JSON marshalling.

    • UnmarshalJSON(data []byte) error function implementation for JSON unmarshalling.

  • InvalidTypeNameErr - error for invalid enum type name, returned by Of(name string) (Type, error) function

4.3. Example Color enum contract

4.3.1. Global variables

Enum has global variables with enum values, which can be used in a type-safe manner.

package color

var (
	Undefined = baseColor{name: "Undefined"} // Undefined value
	Red       = baseColor{name: "Red"}       // Red value
	Green     = baseColor{name: "Green"}     // Green value
	Blue      = baseColor{name: "Blue"}      // Blue value
)

4.3.2. Methods

  • String() string — transforms enum to string value (implements fmt.Stringer interface)

  • Values() []Type — returns a new slice consisting of all the values of this enum.

  • Of(name string) (Type, error) — maps string value to enum value. Returns the enum value or InvalidColorNameErr if the value is not found.

  • OfOrUndefined(name string) Type — maps string value to enum value. Returns the enum value or Undefined if the value is not found.

  • ToJSONMarshallable() MarshallableType — transforms enum to MarshallableType (implements json.Marshaler and json.Unmarshaler interfaces)

4.3.3. MarshallableType

MarshallableColor is a special type for JSON marshalling. Standard Color enum (interface) does not support JSON marshalling. To marshal the enum, use the MarshallableColor intermediate type.

  • MarshalJSON() ([]byte, error) - marshals the enum to JSON.

  • UnmarshalJSON(data []byte) error - unmarshals the enum from JSON.

  • ToEnum() Color - converts MarshallableColor to Color enum.

5. License

The generator is licensed under the MIT License. License available at LICENSE.

6. Contributing

No contribution policy has been defined yet. It is a tiny, single-contributor project.

The project is considered feature-complete at the moment. Most likely, will be updated for bug fixing and vulnerability patches only.

In case the author cannot maintain the project, a new strategy will be created to keep the project alive.

About

Project with Go enum code generator as a sealed interface

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages