golang学习笔记---面向对象
封装:
package main import ( "fmt" ) type Foo struct { baz string } func (f *Foo) echo() { fmt.Println(f.baz) } func main() { f := Foo{baz: "hello,world"} f.echo() }
func (f *Foo) echo() {----其中(f *Foo)是接收者
package main import ( "fmt" ) 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 Bar struct {
Foo
}---Foo是一个匿名字段,Bar 结构体拥有了Foo的所欲特性,
多肽:
package main import ( "fmt" ) type Foo interface { qux() } type Bar struct{} type Baz struct{} func (b Bar) qux() {} func (b Baz) qux() {} func main() { var f Foo f = Baz{} fmt.Println(f) f = Bar{} fmt.Println(f) }
package main import ( "fmt" ) type Foo interface { qux() } type Bar struct{} type Baz struct{} func (b Bar) qux() { fmt.Println("Bar") } func (b Baz) qux() { fmt.Println("Baz") } func main() { var f Foo f = Baz{} f.qux() f = Bar{} f.qux() }