go语言:内嵌二义性(ambiguous selector )

内嵌两个结构体中有相同字段会发生二义性。
先看代码:

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

发布了19 篇原创文章 · 获赞 2 · 访问量 679

猜你喜欢

转载自blog.csdn.net/weixin_43465618/article/details/104589903