This article is based on Go 1.13.

The stringer command aims to automate the creation of methods that satisfy the [fmt.Stringer](https://golang.org/pkg/fmt/#Stringer). It generates String() for specified types that describe them as a string.

Case

The documentation of the command provides an example I will use to study the command. Here is the case:

Image for post

Here is the output:

1

Generating logs with the value of the constants can be a bit confusing.

Let’s generate the String() method with the command stringer -type=Pill:

Image for post

A new function String() has been generated. Here is the new output when running the previous code:

Aspirin

The type now describes itself as string rather than its inner value.

stringer also works perfectly with the command go generate, making it even more powerful. It is as easy as adding the following instruction in the code:

Image for post

Then, running go generate command will automatically generate the new functions for all your types.

#golang #go

Go: Stringer Command, Efficiency Through Code Generation
9.55 GEEK