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.

GoData Integrity

Code

gosnippet
24 lines
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

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:`.