aboutsummaryrefslogtreecommitdiff
path: root/src/fmt
diff options
context:
space:
mode:
authorWarren Fernandes <warren.f.fernandes@gmail.com>2018-09-03 12:32:02 -0600
committerKevin Burke <kev@inburke.com>2018-09-06 04:25:17 +0000
commit262d4f321a885908def68adc4bed68428722b954 (patch)
tree9d53dbd31d686a42cc11d9db15e3035e024674f0 /src/fmt
parent4a095b87d30f1f6f7ae01e966f1af5ee63b15c1c (diff)
downloadgo-262d4f321a885908def68adc4bed68428722b954.tar.gz
go-262d4f321a885908def68adc4bed68428722b954.zip
fmt: add example for GoStringer interface
Updates golang/go#27376. Change-Id: Ia8608561eb6a268aa7eae8c39c7098df100b643a Reviewed-on: https://go-review.googlesource.com/133075 Reviewed-by: Kevin Burke <kev@inburke.com> Run-TryBot: Kevin Burke <kev@inburke.com> TryBot-Result: Gobot Gobot <gobot@golang.org>
Diffstat (limited to 'src/fmt')
-rw-r--r--src/fmt/gostringer_example_test.go59
1 files changed, 59 insertions, 0 deletions
diff --git a/src/fmt/gostringer_example_test.go b/src/fmt/gostringer_example_test.go
new file mode 100644
index 0000000000..ab19ee3b94
--- /dev/null
+++ b/src/fmt/gostringer_example_test.go
@@ -0,0 +1,59 @@
+// Copyright 2018 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package fmt_test
+
+import (
+ "fmt"
+)
+
+// Address has a City, State and a Country.
+type Address struct {
+ City string
+ State string
+ Country string
+}
+
+// Person has a Name, Age and Address.
+type Person struct {
+ Name string
+ Age uint
+ Addr *Address
+}
+
+// GoString makes Person satisfy the GoStringer interface.
+// The return value is valid Go code that can be used to reproduce the Person struct.
+func (p Person) GoString() string {
+ if p.Addr != nil {
+ 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)
+ }
+ return fmt.Sprintf("Person{Name: %q, Age: %d}", p.Name, int(p.Age))
+}
+
+func ExampleGoStringer() {
+ p1 := Person{
+ Name: "Warren",
+ Age: 31,
+ Addr: &Address{
+ City: "Denver",
+ State: "CO",
+ Country: "U.S.A.",
+ },
+ }
+ // If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p1)` would be similar to
+ // Person{Name:"Warren", Age:0x1f, Addr:(*main.Address)(0x10448240)}
+ fmt.Printf("%#v\n", p1)
+
+ p2 := Person{
+ Name: "Theia",
+ Age: 4,
+ }
+ // If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p2)` would be similar to
+ // Person{Name:"Theia", Age:0x4, Addr:(*main.Address)(nil)}
+ fmt.Printf("%#v\n", p2)
+
+ // Output:
+ // Person{Name: "Warren", Age: 31, Addr: &Address{City: "Denver", State: "CO", Country: "U.S.A."}}
+ // Person{Name: "Theia", Age: 4}
+}