Stringer Interface Customizes Print Output
Implement the fmt Stringer interface so Println, Printf %v, and logging render a type in one controlled form instead of raw struct braces.
Code
package main
import "fmt"
type Region struct {
Code string
Name string
}
// 实现 fmt.Stringer:Println、Printf 的 %v 都会调用 String
func (r Region) String() string {
return fmt.Sprintf("%s (%s)", r.Name, r.Code)
}
func main() {
regions := []Region{
{Code: "eu-west-1", Name: "Ireland"},
{Code: "ap-southeast-2", Name: "Sydney"},
}
fmt.Println(regions) // 每个元素走 String()
fmt.Printf("%v\n", regions[0]) // %v 走 String()
fmt.Printf("go-syntax: %#v\n", regions[0]) // %#v 走 Go 语法表示,不经 Stringer
}What the code does
Stringer Interface Customizes Print Output is built around the functions String and main.
Applying it
Entry signature: func (r Region) String() string
Running the file prints labeled results such as go-syntax: — each operation’s effect is visible in the output.
main is the driver: it invokes String before returning.
Statements that matter most here
return fmt.Sprintf("%s (%s)", r.Name, r.Code)
func main() {
regions := []Region{
{Code: "eu-west-1", Name: "Ireland"},
{Code: "ap-southeast-2", Name: "Sydney"},
}
fmt.Println(regions) // 每个元素走 String()
fmt.Printf("%v\n", regions[0]) // %v 走 String()
fmt.Printf("go-syntax: %#v\n", regions[0]) // %#v 走 Go 语法表示,不经 Stringer
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Stringer Interface Customizes Print Output print when run?
- Run it as a complete program — the output lines carry labels such as `go-syntax:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.