内容简介:golang并非完全面向对象的程序语言,为了实现面向对象的继承这一神奇的功能,golang允许struct间使用匿名引入的方式实现对象属性方法的组合
摘要
golang并非完全面向对象的程序语言,为了实现面向对象的继承这一神奇的功能,golang允许struct间使用匿名引入的方式实现对象属性方法的组合
组合使用注意项
- 使用匿名引入的方式来组合其他struct
- 默认优先调用外层方法
- 可以指定匿名struct以调用内层方法
代码事例
package main
import (
"fmt"
)
type People struct{}
type People2 struct{}
func (p *People) ShowA() {
fmt.Println("showA")
p.ShowB()
}
func (p *People) ShowB() {
fmt.Println("showB")
}
func (p *People) ShowC() {
fmt.Println("showC")
}
func (p *People) ShowD() {
fmt.Println("People:showD")
}
func (p *People2) ShowD() {
fmt.Println("People2:showD")
}
type Teacher struct {
People //组合People
People2 //组合People2
}
func (t *Teacher) ShowB() {
fmt.Println("teacher showB")
}
func (t *Teacher) ShowC(arg string) {
fmt.Println(arg)
}
func main() {
t := Teacher{}
//print showA
//print showB
t.ShowA()
//print teacher showB
t.ShowB()
//print showB
t.People.ShowB()
//print test
t.ShowC("test")
//print showC
t.People.ShowC()
//因为组合方法中多次包含ShowD,所以调用时必须显示指定匿名方法
//print People2:showD
t.People2.ShowD()
}
以上所述就是小编给大家介绍的《golang 使用组合的方式实现继承》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 组合还是继承,这是一个问题?——由模式谈面向对象的原则之多用组合、少用继承
- 组合优于继承
- React - 组合 vs 继承
- Golang OOP、继承、组合、接口
- Golang中匿名组合实现伪继承
- 如何理解go语言提倡组合,不提倡继承
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。