理解 go 嵌套结构

Luc*_*hez 3 go data-structures

我试图理解 go 中的嵌套结构,所以我做了一个小测试:(游乐场

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
}
Run Code Online (Sandbox Code Playgroud)

那么最后两行是如何以及为什么起作用的呢?它们是一样的吗?我应该使用哪个?

Ain*_*r-G 5

他们是一样的。请参阅选择器的 Go 规范

x对于typeT*TwhereT不是指针或接口类型的值,表示存在此类 的x.f最浅深度的字段或方法。如果不存在深度最浅的选择器表达式,则该选择器表达式是非法的。Tff

请注意,这意味着b.a如果 typeB在相同深度嵌入具有相同字段的两种类型,则这是非法的:

type A1 struct{ a string }
type A2 struct{ a string }
type B struct {
    A1
    A2
}

// ...
b := B{A1{"a1"}, A2{"a2"}}
fmt.Println(b.a) // Error: ambiguous selector b.a
Run Code Online (Sandbox Code Playgroud)

游乐场:http://play.golang.org/p/PTqm-HzBDr