内嵌两个结构体中有相同字段会发生二义性。
先看代码:
package main
import "fmt"
type Shape struct {
id int
}
type Object struct {
id int
}
type Color struct {
//Object
id int
}
type Rect struct {
Shape
*Color
}
func main() {
r := Rect{
Shape: Shape{id:1},
//Color: &Color{Object:Object{id:2}},
Color: &Color{id:2},
}
fmt.Println(r.id) //报错ambiguous selector r.id
fmt.Println(r.Shape.id) //正确用法
}
上面会报错:
./main.go:31:15: ambiguous selector r.id
r.id不知道引用哪个id。
但是,如果内嵌的id不在同一层级不会报错。而且总是引用前一个层级的id。稍微修改一下上面代码:
package main
import "fmt"
type Shape struct {
id int
}
type Object struct {
id int
}
type Color struct {
Object
//id int
}
type Rect struct {
Shape
*Color
}
func main() {
r := Rect{
Shape: Shape{id:1},
Color: &Color{Object:Object{id:2}},
//Color: &Color{id:2},
}
fmt.Println(r.id)
}
这个正常,输出:1