笔记 - 从PHP到Go的封装、继承、多态

# 封装
type Foo struct{
    baz string
}

func(f *Foo) echo() {
    fmt.println(f.baz)
}

func main() {
    f := Foo{baz:"hello, struct"}
    f.echo()
}

#继承
type Foo struct{
    baz string
}
type Bar struct{
    Foo
}

func(f *Foo) echo() {
    fmt.println(f.baz)
}

func main() {
    b := Bar{Foo{baz:"hello, struct"}}
    b.echo()
}

# 多态
type Foo interface{
    qux()
}

type Bar struct{}
type Baz struct{}

func(b Bar) qux(){}
func(b Baz) qux(){}

func main() {
    var f Foo

    f = Bar{}
    f = Baz{}
    fmt.println(f)
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 7

不叫继承,叫组合才更准确吧 :smile:

1年前 评论
ChenAfrica (楼主) 1年前

我也是从PHP转go 了,感觉php没有前途了。Go语言没有类啊,更没有什么继承多态,go会自动加载。我写go自己也做笔记,写博客你可以看看allgoodsfree.com/category/programm...

1年前 评论
huangxu 1年前
tsingyan 1年前
Luson

套娃

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!