英文:
Go, %v format invoking String() for a nested struct
问题
在下面的代码中,我期望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)
}
英文:
In the following code, I would expect fmt.Printf("%v\n", 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\n", a)
fmt.Printf("%v\n", b)
}
答案1
得分: 3
fmt
不会递归地查找fmt.Stringer
。
如果参数是一个fmt.Stringer
,它将调用String()
方法并打印结果。如果没有String()
方法,fmt
将使用反射迭代字段以获取值。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论