When printing a struct with nested struct which has a String() implemented, the %v
format prints an 'unexpected' value per our understanding.
Below is the code snippet.
package main
import (
"fmt"
)
type Inner struct {
}
type A struct {
Inner
FieldA string
}
func (i Inner) String() string {
return "anything"
}
func main() {
myA := A{FieldA: "A"}
fmt.Printf("%v", myA)
}
We expect the output to be
{anything A}
But the actual result is
anything
Why this result? It seems FieldA
is ignored? To make it more confusing, if we have two nested structs where both of them have String() implemented, the output is expected.
package main
import (
"fmt"
)
type Inner struct {
}
type InnerAgain struct {
}
type A struct {
Inner
InnerAgain
FieldA string
}
func (i Inner) String() string {
return "anything"
}
func (i InnerAgain) String() string {
return "nothing"
}
func main() {
myA := A{FieldA: "A"}
fmt.Printf("%v", myA)
}
The output is
{anything nothing A}
...