理解Go语言嵌套结构体

3
我正在尝试理解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
}

那么,为什么最后两行代码能够起作用?它们是相同的吗?我应该使用哪一个?
1个回答

5
它们是相同的。请参见Go规范中关于选择器的内容
对于类型为T*T的值x,其中T不是指针或接口类型,在T中具有最浅深度的f字段或方法被表示为x.f。如果最浅深度上没有恰好一个f,则选择器表达式是非法的。
请注意,这意味着如果类型B嵌入了具有相同字段的两种类型,则b.a是非法的:
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

示例代码: http://play.golang.org/p/PTqm-HzBDr.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接