耐心和持久胜过激烈和狂热。
哈喽大家好,我是陈明勇,今天分享的内容是在 Go 里面使用组合的思想实现“继承”。如果本文对你有帮助,不妨点个赞,如果你是 Go 语言初学者,不妨点个关注,一起成长一起进步,如果本文有错误的地方,欢迎指出!
前言GoGoGoGo
类型嵌入
Go
结构体类型嵌入
import "fmt"
type Person struct {
Name string
Age int
}
func (p Person) Introduce() {
fmt.Printf("大家好,我叫%s,我今年%d岁了。\n", p.Name, p.Age)
}
type Student struct {
Person
School string
}
func (s Student) GoToTheClass() {
fmt.Println("去上课...")
}
func main() {
student := Student{}
student.Name = "小明"
student.Age = 18
student.School = "太阳系大学"
// 执行 Person 类型的 Introduce 方法
student.Introduce()
// 执行自身的 GoToTheClass 方法
student.GoToTheClass()
}
执行结果:
大家好,我叫小明,我今年18岁了。
去上课...
PersonNameAgeIntroduceStudentSchoolGoToTheClass 方法PersonStudentstudentstudentNameAgeIntroduceStudentStudentPersonPersonStudent
接口类型嵌入
type Coder interface {
Code()
}
type Tester interface {
Test()
}
type TesterCoder interface {
Tester
Coder
}
CoderCodeTesterTestTesterCoderCoderTesterTesterCoderCodeTestGo
小结
Go
“继承”的实现,能够提高代码的复用性,代码的维护性和扩展性也得以提高。