Go 語言并不是傳統(tǒng)意義上的面向?qū)ο笳Z言,但是實現(xiàn)很小的面向?qū)ο蟮臋C制。
匿名嵌入并不是繼承,無法實現(xiàn)多態(tài)處理,雖然配合方法集,可用接口來實現(xiàn)一些類似操作,但是其本質(zhì)是完全不同的。
type Animal struct { 聲明Animal
name string
age int
}
type Cat struct {
Animal 匿名字段
teeth string "牙" "牙" 不是注釋,字段標簽(tag)不是注釋,是用來描述字段的元數(shù)據(jù),是struct的一部分
leg int
}
type Animal struct { 聲明Animal類
name string
age int
}
type AnimalAction interface { 聲明AnimalAction 接口類
eat() 聲明func
voice() 聲明func
}
func (a Animal) eat(){ Animal實現(xiàn)接口AnimalAction 方法eat()
fmt.Print("eat")
}
func (a Animal) voice(){ Animal實現(xiàn)接口AnimalAction 方法voice()
fmt.Print("voice")
}
type Cat struct { 聲明Cat類
Animal 匿名字段Animal 嵌入類型
teeth string "牙"
leg int
}
type NewAction interface { 聲明NewAction 接口類
run()
sing(s func(name string)) 聲明閉包sing
}
func (c Cat) eat(){ Cat實現(xiàn) func eat(),類似繼承的重寫,但不是重寫。
c.Animal.eat() Cat調(diào)用Animal func eat(),類似super.eat() 但不是調(diào)用父類方法
fmt.Print("cat eat")
}
func (c Cat) run(){ Cat實現(xiàn)NewAction func run()
fmt.Print("cat run")
}
func (c Cat) sing(s func(name string)){ 實現(xiàn)閉包sing
s("cat")
}
func test(){
a := Animal{
"a",
12,
}
a.eat()
a.voice()
c := Cat{
Animal{
"cat",
1,
},
"尖牙",
4,
}
c.eat()
c.voice()
c.run()
c.sing(func(name string) { 調(diào)用閉包
fmt.Print("\n" + name + "sing")
})
}