go语言学习笔记八 继承

继承基本使用

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  // 继承StudentBase的属性和方法
	Hobby string
}

type Student2 struct {
	Student StudentBase  // 嵌套一个结构体并且命名 称为组合
	Hobby string
}


func main() {
	s := &Student{}
	// 可以简写为s.Name = "小张"
	// 查找顺序 现在Student中查找,没有属性再查找StudentBase,如果还没有会报错
	s.StudentBase.Name = "小张"
	s.StudentBase.Age = 10
	s.StudentBase.Score = 99.5
	s.Hobby = "打篮球"
	// 可以简写为 s.ShowInfo()
	s.StudentBase.ShowInfo()
	fmt.Printf("2.Student独有的字段Hobby:%v\n", s.Hobby)

	s2 := &Student2{}
	// 组合方式不能简写为s2.Name
	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:小明

猜你喜欢

转载自blog.csdn.net/qq_38165374/article/details/105349285