这是我参与更文挑战的第3天,活动详情查看: 更文挑战
1. 结构体嵌套
假设老师只在一个学校任职,只教一个班级学生。
//假设老师只在一个学校任职,只教一个班级学生
type student struct{
name string
age int
class int
school string
}
type teacher struct{
name string
age int
course string //老师说授课程
class int
school string
}
从上面可以看出学生与老师的班级与学校重叠,这个时候就可以单独将班级与学校信息抽取为一个结构体,再嵌套在学生与教师结构体中。
程序修改为:
package main
import "fmt"
type class_school struct{
class int
school string
}
type student struct{
name string
age int
c_s class_school
}
type teacher struct{
name string
age int
course string //老师讲授课程
c_s class_school
}
func main(){
s1 := student{
name : "心安",
age : 5,
c_s:class_school{
class : 8,
school : "叮当幼儿园",
},
}
t1 := teacher{
name : "花花老师",
age : 27,
course : "美术课",
c_s :class_school{
class : 4,
school :"叮当幼儿园",
},
}
fmt.Println(s1)
fmt.Println(t1)
}
输出结果:
{心安 5 {8 叮当幼儿园}}
{花花老师 27 美术课 {4 叮当幼儿园}}
Go语言语法糖: 通过匿名嵌套获得嵌套的结构体的元素。
package main
import "fmt"
type class_school struct{
class int
school string
}
type student struct{
name string
age int
//c_s class_school
//匿名嵌套
class_school
}
type teacher struct{
name string
age int
course string //老师讲授课程
c_s class_school
}
func main(){
s1 := student{
name : "心安",
age : 5,
class_school:class_school{
class : 8,
school : "叮当幼儿园",
},
}
t1 := teacher{
name : "花花老师",
age : 27,
course : "美术课",
c_s :class_school{
class : 4,
school :"叮当幼儿园",
},
}
//Go语言语法糖
fmt.Println(t1.c_s.school)
fmt.Println(s1.school)
}
输出结果:
叮当幼儿园
叮当幼儿园
2. 继承
继承指的是让某个类型的对象获得另一个类型的对象的属性的方法。
package main
import "fmt"
type people struct{
name string
age int
}
func (p people) speak(){
fmt.Printf("%s正在讲话\n",p.name)
}
type student struct{
no string
//继承
people
}
func (s student) study(){
fmt.Printf("%s每天学习\n",s.name)
}
func main(){
s1 := student{
people:people{
name : "xiaoxiao",
age : 2,
},
no :"0023",
}
fmt.Println(s1)
s1.speak()
s1.study()
}
输出结果:
{0023 {xiaoxiao 2}}
xiaoxiao正在讲话
xiaoxiao每天学习