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