In the following code, I would expect fmt.Printf("%v ", a)
to invoke String() of its member of type myTypeB, but this is not happening ? Why ?
package main
import "fmt"
type myTypeA struct {
b myTypeB
}
type myTypeB struct {
c string
d int
}
func (b myTypeB) String() string {
return "myTypeB custom"
}
func main() {
a:= myTypeA{myTypeB{"hello", 1}};
b:= myTypeB{"hello", 1}
fmt.Printf("%v
", a)
fmt.Printf("%v
", b)
}
fmt
doesn't look for fmt.Stringer
recursively.
If the argument is a fmt.Stringer
, it will invoke the String()
method, and print the results. If it doesn't have a String()
method, fmt
will iterate over the fields using reflection to obtain the value.