一、结构体嵌套
package main
import "fmt"
type Student struct {
Name string
Age int
Score int
}
func (stu *Student) ShowInfo() {
fmt.Printf("学生名=%v 年龄= %v 成绩=%v\n", stu.Name, stu.Age, stu.Score)
}
func (stu *Student) SetScore(score int) {
stu.Score = score
}
type Pupil struct {
Student
}
func (p *Pupil) testing() {
fmt.Println("小学生正在考试中")
}
type Graduate struct {
Student
}
func (p *Graduate) testing() {
fmt.Println("DA学生正在考试中")
}
func main() {
var pupil = &Pupil{}
pupil.Student.Name = "tom"
pupil.Student.Age = 8
pupil.testing()
pupil.Student.SetScore(30)
pupil.Student.ShowInfo()
var granduate = &Graduate{}
granduate.Student.Name = "w"
granduate.Student.Age =20
granduate.testing()
granduate.Student.SetScore(3)
granduate.Student.ShowInfo()
}
运行结果:
小学生正在考试中
学生名=tom 年龄= 8 成绩=30
DA学生正在考试中
学生名=w 年龄= 20 成绩=3
无论大学生小学生都有年龄和分数,不一样的就是testing()方法是大学生、小学生在考试,所以单独用Pupil和Graduate指针去接收,ShowInfo()和SetScore()用student指针去接收
二、继承
好处:复用性、维护性、扩展性
type Animal struct {
Name string
age int
}
func (animal *Animal) SayOk() {
fmt.Println("animal say", animal.Name)
}
func (animal *Animal) hello() {
fmt.Println("animal hello", animal.Name)
}
type Dog struct {
Animal
}
func main() {
var dog Dog
dog.Animal.Name = "哈市 dog"
dog.Animal.age = 20
dog.Animal.SayOk()
dog.Animal.hello()
dog.Name = "后代dog"
dog.age = 1
dog.SayOk()
dog.hello()
}
运行结果:
animal say 哈市 dog
animal hello 哈市 dog
animal say 后代dog
animal hello 后代dog
1.直接访问dog的字段或者方法,dog.Name
2.编译的时候会先看dog对应的有没有Name,如果有则直接滴啊用dog类型的Name,如果没有就去看animal的结构体中有没有这个字段
3.当结构体和匿名结构体都有相同的字段和方法,采用就近原则,如果要指定那就指定一下
type Animal struct {
Name string
age int
}
func (animal *Animal) SayOk() {
fmt.Println("animal say", animal.Name)
}
func (animal *Animal) hello() {
fmt.Println("animal hello", animal.Name)
}
type Dog struct {
Animal
Name string
}
func (dog *Dog) hello() {
fmt.Println("dog hello", dog.Name)
}
func main() {
var dog Dog
dog.Animal.Name = "哈市 dog"
dog.Name = "后代dog"
dog.Animal.age = 20
dog.Animal.SayOk()
dog.Animal.hello()
dog.age = 1
dog.SayOk()
dog.hello()
}
运行结果:
animal say 哈市 dog
animal hello 哈市 dog
animal say 哈市 dog
dog hello 后代dog