在下面的代码中,我希望 fmt.Printf("%v\n", a)
调用其类型为 myTypeB 的成员的 String(),但这并没有发生?为什么?
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\n", a)
fmt.Printf("%v\n", b)
}
最佳答案
fmt
不会递归地查找 fmt.Stringer
。
如果参数是 fmt.Stringer
,它将调用 String()
方法,并打印结果。如果它没有 String()
方法,fmt
将使用反射遍历字段以获取值。
关于Go,%v 格式为嵌套结构调用 String(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26020726/