目录
前言
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
“继承”的实现,能够提高代码的复用性,代码的维护性和扩展性也得以提高。
您可能感兴趣的文章: