Golang 继承 注意事项

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} {格力空调 广东珠海}

}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值