Stringer in Go
A String method changes how fmt prints your type.
type Stars int
func (s Stars) String() string {
if s < 0 || s > 3 {
return "invalid"
}
return strings.Repeat("*", int(s)) + strings.Repeat(".", 3-int(s))
}
type Step struct {
Title string
Stars Stars
}
func (s Step) String() string {
return fmt.Sprintf("%-12s %s", s.Title, s.Stars)
}
func show() string {
return fmt.Sprint(Step{Title: "Slices", Stars: 2})
}
How it works
fmt.Stringeris the one-method interface fmt looks for.- Use a value receiver, or printing a value will not find it.
- Never call fmt.Sprintf(\u0022%v\u0022, x) inside x.String().
Keywords and builtins used here
funcifintreturnstringstructtype
The run, in numbers
- Lines
- 21
- Characters to type
- 362
- Tokens
- 110
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 63 seconds.
Step 2 of 3 in Standard interfaces, step 11 of 19 in Interfaces & generics.