Member-only story
Go: Stringer Command, Efficiency Through Code Generation
ℹ️ This article is based on Go 1.13.
The stringer
command aims to automate the creation of methods that satisfy the 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:
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…