enumerator

command
v0.0.0-...-897bb11 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2023 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Enumerator is a tool to automate the creation of simple enums. Given the name of a (signed or unsigned) integer type T that has constants defined, enumerator will create a new self-contained Go source file implementing

func ParseT(string) (T, error)
func (t T) String() string

and for each value X

func (t T) IsX() bool

The file is created in the same package and directory as the package that defines T. This tool is designed to be used with go generate.

For example, given this snippet,

package painkiller

type Pill int

const (
	Placebo Pill = iota
	Aspirin
	Ibuprofen
	Paracetamol
	Acetaminophen = Paracetamol
)

running this command

enumerator -type=Pill

in the same directory will create the file pill_string.go, in package painkiller, containing definitions of

func ParsePill() (Pill, error)
func (Pill) String() string
func (Pill) IsPlacebo() bool
func (Pill) IsAspirin() bool
func (Pill) IsIbuprofen() bool
func (Pill) IsParacetamol() bool

The String method will translate the value of a Pill constant to the string representation of the respective constant name, so that the call fmt.Print(painkiller.Aspirin) will print the string "Aspirin".

The Parse method performs the inverse, so that the call ParsePill("Aspirin") will return painkiller.Aspirin, nil.

Typically this process would be run using go generate, like this:

//go:generate stringer -type=Pill

If multiple constants have the same value, the lexically first matching name will be used (in the example, Acetaminophen will print as "Paracetamol").

The -type flag is required to contain the type to generate methods for.

The -linecomment flag tells enumerator to generate the text of any line comment, trimmed of leading spaces, instead of the constant name. For instance, if it was desired to have the names in lower case

Aspirin // aspirin

The -trimprefix flag tells enumerator to remove any type name prefixes. For instance, if we prefixed our values with Pill, like

PillAspirin

a IsAspirin() method would still be generated, painkiller.Aspirin.String() would return "Aspirin" and ParsePill("Aspirin") would return painkiller.Aspirin.

The -empty flag tells enumerator to generate a method to check whether the underlying value is 0. This is useful when an enum is defined using iota+1. For instance, with the following

type YesNo uint8

const (
	Yes YesNo = iota + 1
	No
)

we would be able to check whether a value x had not been set to Yes or No by using the boolean value returned by x.Empty().

Jump to

Keyboard shortcuts

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