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

Golang
384
0
0
2022-11-10
标签   Golang基础
# 封装
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)
}