使用%v格式调用String()方法来打印嵌套结构体。

huangapple go评论67阅读模式
英文:

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)
}

Playground链接

英文:

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)
}

Playground link

答案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.

huangapple
  • 本文由 发表于 2014年9月24日 23:23:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/26020726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定