继承基本使用
package main
import "fmt"
type StudentBase struct {
Name string
Age int
Score float64
}
func (p *StudentBase) ShowInfo() {
fmt.Printf("1.StudentBase Name:%v Age:%v Score:%v\n", p.Name, p.Age, p.Score)
}
type Student struct {
StudentBase
Hobby string
}
type Student2 struct {
Student StudentBase
Hobby string
}
func main() {
s := &Student{}
s.StudentBase.Name = "小张"
s.StudentBase.Age = 10
s.StudentBase.Score = 99.5
s.Hobby = "打篮球"
s.StudentBase.ShowInfo()
fmt.Printf("2.Student独有的字段Hobby:%v\n", s.Hobby)
s2 := &Student2{}
s2.Student.Name = "小明"
fmt.Printf("3.s2.Student.Name:%v\n", s2.Student.Name)
}
输出
1.StudentBase Name:小张 Age:10 Score:99.5
2.Student独有的字段Hobby:打篮球
3.s2.Student.Name:小明