| 1 |
// Copyright 2018 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package fmt_test |
| 6 |
|
| 7 |
import ( |
| 8 |
"fmt" |
| 9 |
) |
| 10 |
|
| 11 |
// Address has a City, State and a Country. |
| 12 |
type Address struct { |
| 13 |
City string |
| 14 |
State string |
| 15 |
Country string |
| 16 |
} |
| 17 |
|
| 18 |
// Person has a Name, Age and Address. |
| 19 |
type Person struct { |
| 20 |
Name string |
| 21 |
Age uint |
| 22 |
Addr *Address |
| 23 |
} |
| 24 |
|
| 25 |
// GoString makes Person satisfy the GoStringer interface. |
| 26 |
// The return value is valid Go code that can be used to reproduce the Person struct. |
| 27 |
func (p Person) GoString() string { |
| 28 |
if p.Addr != nil { |
| 29 |
return fmt.Sprintf("Person{Name: %q, Age: %d, Addr: &Address{City: %q, State: %q, Country: %q}}", p.Name, int(p.Age), p.Addr.City, p.Addr.State, p.Addr.Country) |
| 30 |
} |
| 31 |
return fmt.Sprintf("Person{Name: %q, Age: %d}", p.Name, int(p.Age)) |
| 32 |
} |
| 33 |
|
| 34 |
func ExampleGoStringer() { |
| 35 |
p1 := Person{ |
| 36 |
Name: "Warren", |
| 37 |
Age: 31, |
| 38 |
Addr: &Address{ |
| 39 |
City: "Denver", |
| 40 |
State: "CO", |
| 41 |
Country: "U.S.A.", |
| 42 |
}, |
| 43 |
} |
| 44 |
// If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p1)` would be similar to |
| 45 |
// Person{Name:"Warren", Age:0x1f, Addr:(*main.Address)(0x10448240)} |
| 46 |
fmt.Printf("%#v\n", p1) |
| 47 |
|
| 48 |
p2 := Person{ |
| 49 |
Name: "Theia", |
| 50 |
Age: 4, |
| 51 |
} |
| 52 |
// If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p2)` would be similar to |
| 53 |
// Person{Name:"Theia", Age:0x4, Addr:(*main.Address)(nil)} |
| 54 |
fmt.Printf("%#v\n", p2) |
| 55 |
|
| 56 |
// Output: |
| 57 |
// Person{Name: "Warren", Age: 31, Addr: &Address{City: "Denver", State: "CO", Country: "U.S.A."}} |
| 58 |
// Person{Name: "Theia", Age: 4} |
| 59 |
} |