我正在尝试理解Go语言中的嵌套结构体,因此我进行了一个小测试: (playground)
那么,为什么最后两行代码能够起作用?它们是相同的吗?我应该使用哪一个?
type A struct {
a string
}
type B struct {
A
b string
}
func main() {
b := B{A{"a val"}, "b val"}
fmt.Printf("%T -> %v\n", b, b) // B has a nested A and some values
// main.B -> {{a val} b val}
fmt.Println("b.b ->", b.b) // B's own value
// b.b -> b val
fmt.Println("b.A.a ->", b.A.a) // B's nested value
// b.a -> a val
fmt.Println("b.a ->", b.a) // B's nested value? or own value?
// b.a -> a val
}
那么,为什么最后两行代码能够起作用?它们是相同的吗?我应该使用哪一个?