1 // A struct and a named func type have a builtin String().
2 //
3 // fmt takes ...Stringer, so a type with no declared String() had no printable
4 // form: stage4 accepted the call and printed '?', legacy refused the package.
5 // The compiler now synthesizes the method for every struct and named func type
6 // that does not declare one; a declared String() always wins. The struct body
7 // walks the type descriptor in runtime (field names, offsets, nested types), and
8 // a named func type renders its signature.
9 package main
10 11 import (
12 "fmt"
13 "os"
14 )
15 16 type inner struct {
17 n int32
18 txt string
19 }
20 21 type point struct {
22 x, y int32
23 name string
24 next *point
25 vals []int32
26 in inner
27 }
28 29 type callback func(a int32, s string) (int32, error)
30 31 type custom struct {
32 n int32
33 }
34 35 func (c *custom) String() (s string) { return "custom" }
36 37 func check(label, got, want string) {
38 if got != want {
39 fmt.Printf("FAIL %s: got %s want %s\n", label, got, want)
40 os.Exit(1)
41 }
42 }
43 44 func main() {
45 // Termination: a batch program must still be stoppable, so the entry
46 // handles the channel the runtime closes on SIGINT/SIGTERM.
47 select {
48 case <-shutdown:
49 return
50 default:
51 }
52 53 p := point{x: 1, y: -2, name: "p", in: inner{n: 7, txt: "t"}}
54 const want = "{x:1 y:-2 name:p next:nil vals:[] in:{n:7 txt:t}}"
55 check("struct", fmt.Sprintf("%v", p), want)
56 check("struct+", fmt.Sprintf("%+v", p), want)
57 check("method", p.String(), want)
58 var cb callback
59 check("func", fmt.Sprintf("%v", cb), "func(a int32, s string) (int32, error)")
60 check("override", fmt.Sprintf("%v", custom{n: 3}), "custom")
61 fmt.Println("builtin string render ok")
62 }
63