1.结构体嵌入两个(或多个)匿名结构体,如果两个匿名结构体有相同的字段和方法
(同时结构体本身没有同名的字段和方法),在访问时,就必须明确指定匿名结构名字否则编译错误
type A struct {
Name string
age int
}
type B struct {
Name string
score int
A
}
type c struct {
a A
B
}
func (a *A) SayHello (){
fmt.Println("A Say hello",a.age,a.Name)
}
func (a *A) SayBaybay() {
fmt.Println("A Say Baybay",a.age,a.Name)
}
func (b *B)SayHello (){ //体现第3点
fmt.Println("B SayOk",b.Name)
}
2.如果struct嵌套了一个有名结构体,这种模式就是组合,如果是组合关系,那么访问组合的结构体的字段或方法时,
必须带上结构体的名字
type A struct {
Name string
age int
}
type c struct {
a A
}
3 嵌套匿名结构体后,也可以在创建结构体变量(实例)时,直接指定各个匿名结构体字段的值
graduate := Graduate{
Student{
"贾蓉",
21,
65,
},
}
// 组合结构用的 用指针传递
type Goods struct {
name string
price float64
}
type Brand struct {
Name string
address string
}
type Aircondition struct {
* Goods // 同时也可以嵌套指针 效率更高
* Brand
}
func main() {
var greenAircondition = Aircondition{
&Goods{
name:"格力空调",
price:3888.8,
},
&Brand{
Name:"格力空调",
address:"广东珠海",
},
}
fmt.Println("Aircondition informations",greenAircondition) // Aircondition informations {0xc0420023e0 0xc042002400}
//* 那怎么取出来呢? 用*
fmt.Println("Aircondition informations",*greenAircondition.Goods,*greenAircondition.Brand)// Aircondition informations {格力空调 3888.8} {格力空调 广东珠海}
}
// 组合结构 用的值传递
type Goods struct {
name string
price float64
}
type Brand struct {
Name string
address string
}
type Aircondition struct {
Goods // 同时也可以嵌套指针 指针 效率更高
Brand
}
func main() {
var greenAircondition = Aircondition{
Goods{
name:"格力空调",
price:3888.8,
},
Brand{
Name:"格力空调",
address:"广东珠海",
},
}
fmt.Println("Aircondition informations",greenAircondition) // Aircondition informations {0xc0420023e0 0xc042002400}
//* 那怎么取出来呢? 用*
//fmt.Println("Aircondition informations",*greenAircondition.Goods,*greenAircondition.Brand)// Aircondition informations {格力空调 3888.8} {格力空调 广东珠海}
}