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.
The documentation of the command provides an example I will use to study the command. Here is the case:
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
:
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:
Then, running go generate
command will automatically generate the new functions for all your types.
#golang #go