GO语言中没有继承,但是提供了一种扩展与复用。
废话少说,直接上代码:
package ch11
import (
"fmt"
"testing"
)
type Pet struct {
}
func (p *Pet) Speak() {
fmt.Printf("...")
}
func (p *Pet) SpeakTo(host string) {
p.Speak()
fmt.Println("", host)
}
type Dog struct {
p *Pet
}
func (d *Dog) speak(){
fmt.Println("wang")
d.p.Speak()
}
func (d *Dog)SpeakTo(host string) {
d.p.SpeakTo(host)
}
func TestDog(t *testing.T) {
dog := new(Dog)
dog.SpeakTo("chao")
}
以上代码可以优化。因为GO提供一种 提供了一种匿名嵌套类型,我们可以实现组合使用,以上代码优化后为:
package ch11
import (
"fmt"
"testing"
)
//go里没有继承,但是可以扩展与复用,提供了一种匿名嵌套类型
//扩展与复用
type Pet struct {
}
func (p *Pet) Speak() {
fmt.Printf("...")
}
func (p *Pet) SpeakTo(host string) {
p.Speak()
fmt.Println("", host)
}
//匿名嵌套类型
type Dog struct {
//p *Pet
Pet
}
//func (d *Dog) speak(){
// fmt.Println("wang")
// //d.p.Speak()
//}
//func (d *Dog)SpeakTo(host string) {
// d.p.SpeakTo(host)
//}
func TestDog(t *testing.T) {
dog := new(Dog)
dog.SpeakTo("chao")
}
代码地址:https://github.com/yangliuzzu/GO-daily-Study.git
最后
以上就是高高小蝴蝶最近收集整理的关于GO 中实现扩展与复用的全部内容,更多相关GO内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复