Go的继承

1、继承方式

在go语言中,通过匿名字段实现继承操作,代码如下:

package main

import "fmt"

type person struct {
	name string
	age  int
	sex  string
}

//结构体嵌套结构体
type Student struct {
	//通过匿名字段实现继承操作
	person //结构体名称作为结构体成员
	id     int
	score  int
}

func main() {
	var stu Student = Student{person{"张三丰", 190, "男"}, 101, 100}

	stu.id = 101
	//结构体名称.父类成员信息
	stu.name = "张三"
	//stu.person.name="张三"
	stu.score = 100
	stu.sex = "男"
	stu.age = 18

	fmt.Println(stu)

}

2、同名字段处理

采用就进原则,使用子类信息,代码如下:

package main

import "fmt"

type Person struct {
	name string
	age  int
	sex  string
}
type student struct {
	Person
	id    int
	name  string
	score int
}

func main() {
	var stu student = student{Person{"张三疯", 18, "男"}, 102, "张三", 100}
	//采用就进原则 使用子类信息
	stu.name = "张三丰"
	//结构体变量.匿名字段.结构体成员
	//stu.Person.name="张三疯"
	stu.id = 101
	stu.score = 99
	stu.sex = "男"
	stu.age = 18

	fmt.Println(stu)

}

输出结果:

{{张三疯 18} 101 张三丰 99}

3、指针匿名字段

package main

import "fmt"

type person1 struct {
	name string
	age  int
	sex  string
}

type student1 struct {
	*person1 //指针匿名字段
	id       int
	score    int
}

func main() {

	var stu student1 = student1{&person1{"小龙女", 38, "女"}, 105, 66}
	var per = person1{"杨过", 35, "男"}
	//stu.person.name
	//将结构体变量 赋值给结构体指针类型
	stu.person1 = &per
	//stu.person1=new(person1)
	//stu.name = "郭襄"
	//stu.person1.name = "郭小姐"
	//stu.id = 101
	//stu.score = 78

	fmt.Println(stu)
	fmt.Println(stu.name)
	fmt.Println(stu.id)
	fmt.Println(stu.score)
}

输出结果:

{0xc00010e3f0 105 66}
杨过
105 
66  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值