摘要
golang并非完全面向对象的程序语言,为了实现面向对象的继承这一神奇的功能,golang允许struct间使用匿名引入的方式实现对象属性方法的组合
组合使用注意项
使用匿名引入的方式来组合其他struct
默认优先调用外层方法
可以指定匿名struct以调用内层方法
代码事例
package mainimport ( "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()
}
作者:火头陀
链接:https://www.jianshu.com/p/e70c3742404e
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦