stringer

command
v0.0.0-...-dab08d9 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2026 License: MIT Imports: 15 Imported by: 0

README

Stringer

An enhanced version of Go's stringer tool that generates String() methods for integer enum types, plus additional methods for validation, reverse lookup, and JSON marshaling.

The standard stringer tool is one of the most useful tools the Go team has provided. But after years of use, there are common patterns that developers end up maintaining by hand. This tool consolidates those patterns into code generation.

Why integer enums over string enums?

  • Size: Most enumerators fit in a uint8 (1 byte). A string enum is rarely less than 4 bytes.
  • Allocation: Integers don't allocate; strings do.
  • Comparison flexibility: Numeric types enable range checks (e.g., codes 10-20 mean success, >20 means failure) rather than equality-only comparisons.
  • Large dataset efficiency: In the era of large datasets, AI training, and cloud compute, poor data type choices add up.

Install

go get -tool github.com/gostdlib/base/values/generators/stringer

Basic Usage

//go:generate go tool github.com/gostdlib/base/values/generators/stringer -type=Fruit -linecomment

type Fruit uint8

const (
	UnknownFruit Fruit = 0 // Unknown
	Apple        Fruit = 1 // apple
	Orange       Fruit = 2 // orange
)

Running go generate produces a String() method so that Apple.String() returns "apple".

Flags

Flag Description
-type (Required) Comma-separated list of type names (e.g., -type=Pill,Color)
-output Output file name; defaults to <type>_string.go
-trimprefix Prefix to strip from constant names (e.g., -trimprefix=Fruit makes FruitApple output "Apple")
-linecomment Use the line comment text as the string value instead of the constant name
-tags Comma-separated build tags (directory input only)
-valid Generate a Valid() bool method
-invalid Comma-separated values/ranges to mark invalid (e.g., -invalid="0,<4,>=100")
-reverse Generate a Reverse<Type>(s string, caseSensitive bool) (<Type>, bool) function
-replace String replacement pairs for reverse lookup (e.g., -replace=-,_); repeatable
-marshal Generate MarshalJSON() / UnmarshalJSON() methods (requires -reverse, enables -valid)
-marshalinsensitive Case-insensitive UnmarshalJSON (enables -marshal and -reverse)
-list Generate a List<Type>() iter.Seq[<Type>] function yielding all values in order
Flag dependencies
  • -marshal requires -reverse
  • -marshalinsensitive automatically enables -marshal and -reverse
  • -marshal automatically enables -valid
  • -replace requires -reverse
  • -invalid requires -valid or -marshal

Features

Validation (-valid, -invalid)

When receiving enum values from the network, a client/server version mismatch can introduce unexpected values. The Valid() method tells you if a value is a defined constant.

The zero value in Go defaults to 0, which typically represents an "Unknown" state. Use -invalid=0 to treat it as invalid even though it is a defined constant. The -invalid flag supports values and range operators:

-invalid="0"          # single value
-invalid="0,<4,>=100" # combined: 0, less than 4, and >= 100
//go:generate go tool github.com/gostdlib/base/values/generators/stringer -type=Status -linecomment -valid -invalid=0

type Status uint8

const (
	UnknownStatus Status = 0 // Unknown
	Active        Status = 1 // active
	Inactive      Status = 2 // inactive
)

Generated:

func (i Status) Valid() bool { ... }

Active.Valid()        // true
UnknownStatus.Valid() // false (invalid=0)
Status(99).Valid()    // false
Reverse lookup (-reverse)

Convert strings back to enum values, similar to what Protocol Buffers provide. Useful for parsing user input or data from external systems.

//go:generate go tool github.com/gostdlib/base/values/generators/stringer -type=Status -linecomment -reverse

Generated:

func ReverseStatus(s string, caseSensitive bool) (Status, bool)
val, ok := ReverseStatus("active", true)  // case-sensitive
val, ok := ReverseStatus("Active", false) // case-insensitive
String replacement (-replace)

When external data uses different conventions (e.g., hyphens vs. underscores), -replace transforms the input string before lookup:

-replace=-,_    # replace dashes with underscores before lookup

Use \, to escape a literal comma and \\ for a literal backslash.

JSON marshaling (-marshal, -marshalinsensitive)

Generate MarshalJSON() and UnmarshalJSON() methods for JSON encoding/decoding of enum values as strings.

//go:generate go tool github.com/gostdlib/base/values/generators/stringer -type=Color -linecomment -marshalinsensitive

MarshalJSON validates the value before marshaling and returns an error for undefined values. UnmarshalJSON converts the JSON string back to the enum value.

With -marshalinsensitive, unmarshaling accepts any case variation: "red", "Red", and "RED" all resolve to the same value.

Listing values (-list)

Generate a List<Type>() iter.Seq[<Type>] function that yields all defined constant values in order.

//go:generate go tool github.com/gostdlib/base/values/generators/stringer -type=Fruit -linecomment -list

Generated:

func ListFruit() iter.Seq[Fruit]
for fruit := range ListFruit() {
	fmt.Println(fruit)
}
// Output:
// apple
// orange
// banana

Full example

//go:generate go tool github.com/gostdlib/base/values/generators/stringer -type=Fruit -linecomment -valid -invalid=0 -reverse -marshal -list

type Fruit uint8

const (
	UnknownFruit Fruit = 0 // Unknown
	Apple        Fruit = 1 // apple
	Orange       Fruit = 2 // orange
	Banana       Fruit = 3 // banana
)

This generates:

  • func (i Fruit) String() string - returns the line comment text
  • func (i Fruit) Valid() bool - returns false for 0 and undefined values
  • func ReverseFruit(s string, caseSensitive bool) (Fruit, bool) - string-to-value lookup
  • func (i Fruit) MarshalJSON() ([]byte, error) - JSON encoding
  • func (i *Fruit) UnmarshalJSON(data []byte) error - JSON decoding
  • func ListFruit() iter.Seq[Fruit] - iterate over all values in order

Claude Code skill

This repo includes a SKILL.md file that teaches Claude Code how to generate go:generate directives for this tool. When installed, Claude will automatically suggest the correct directive and flags when you define integer enum types.

To install, copy the file into your personal or project skills directory:

# Personal (applies to all your projects)
mkdir -p ~/.claude/skills/stringer
cp SKILL.md ~/.claude/skills/stringer/SKILL.md

# Or project-level (applies to one project)
mkdir -p .claude/skills/stringer
cp SKILL.md .claude/skills/stringer/SKILL.md

You can also invoke it manually in Claude Code with /stringer.

License

See LICENSE for details. This tool is a fork of the original Go stringer tool.

Documentation

Overview

Stringer is a tool to automate the creation of methods that satisfy the fmt.Stringer interface. Given the name of a (signed or unsigned) integer type T that has constants defined, stringer will create a new self-contained Go source file implementing

func (t T) String() string

The file is created in the same package and directory as the package that defines T. It has helpful defaults designed for use with go generate.

Stringer works best with constants that are consecutive values such as created using iota, but creates good code regardless. In the future it might also provide custom support for constant sets that are bit patterns.

For example, given this snippet,

package painkiller

type Pill int

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

running this command

stringer -type=Pill

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

func (Pill) String() string

That 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".

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").

With no arguments, it processes the package in the current directory. Otherwise, the arguments must name a single directory holding a Go package or a set of Go source files that represent a single Go package.

The -type flag accepts a comma-separated list of types so a single run can generate methods for multiple types. The default output file is t_string.go, where t is the lower-cased name of the first type listed. It can be overridden with the -output flag.

Types can also be declared in tests, in which case type declarations in the non-test package or its test variant are preferred over types defined in the package with suffix "_test". The default output file for type declarations in tests is t_string_test.go with t picked as above.

The -linecomment flag tells stringer to generate the text of any line comment, trimmed of leading spaces, instead of the constant name. For instance, if the constants above had a Pill prefix, one could write

PillAspirin // Aspirin

to suppress it in the output.

The -trimprefix flag specifies a prefix to remove from the constant names when generating the string representations. For instance, -trimprefix=Pill would be an alternative way to ensure that PillAspirin.String() == "Aspirin".

Additional Methods

The -valid flag generates a Valid() bool method that returns true if the value is one of the defined constants.

The -invalid flag accepts a comma-separated list of values or ranges that should be considered invalid. For example, -invalid="0,<4,>=100" marks 0, values less than 4, and values greater than or equal to 100 as invalid. This affects the Valid() method and the reverse lookup function.

The -reverse flag generates a Reverse{{Type}}(s string, caseSensitive bool) ({{Type}}, bool) function that performs a reverse lookup from string to enum value.

The -replace flag (can be used multiple times) specifies string replacements to apply in the reverse lookup function. For example, -replace=-,_ will replace dashes with underscores before lookup. Requires -reverse.

The flag supports backslash escaping for special characters:

\,  → literal comma (allows replacing commas)
\\  → literal backslash

For example, -replace=\,,_ replaces commas with underscores.

When multiple -replace flags are used, they are applied sequentially in the order specified. For example, -replace=a,b -replace=b,c will transform "a" to "c" (a→b→c).

The -marshal flag generates MarshalJSON and UnmarshalJSON methods for JSON encoding/decoding. The methods use the String() representation for marshaling and the Reverse{{Type}} function for unmarshaling. MarshalJSON validates the value using Valid() before marshaling, returning an error for invalid values. Requires -reverse and automatically enables -valid.

The -marshalinsensitive flag makes UnmarshalJSON case-insensitive when looking up string values. For example, "red", "Red", and "RED" would all unmarshal to the same value. Automatically enables -marshal (and transitively -reverse and -valid).

The -list flag generates a List{{Type}}() iter.Seq[{{Type}}] function that yields all defined constant values in order.

Jump to

Keyboard shortcuts

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