我似乎在重複說功能,例如。有沒有一種慣用的Go方式來幹下面的代碼:
還有一種方法可以將嬰兒和人類的初始知識轉移到默認構造函數,而不是在創建新的嬰兒和人類時通過?
package main
import (
"fmt"
)
func main() {
h := Human{"good things"}
d := Devil{}
b := Baby{"ga ga"}
b.speak()
h.speak()
d.poisons(&h)
d.poisons(&b)
b.speak()
h.speak()
}
type Human struct {
Knowledge string
}
type Devil struct{}
type Baby struct {
Knowledge string
}
type Knowledgable interface {
changeKnowledge(newKnowledge string)
}
func (d Devil) poisons(creature Knowledgable) {
creature.changeKnowledge(" evil things")
}
func (h Human) speak() {
fmt.Println(h.Knowledge)
}
func (b Baby) speak() {
fmt.Println(b.Knowledge)
}
func (h *Human) changeKnowledge(newKnowledge string) {
h.Knowledge += newKnowledge
}
func (b *Baby) changeKnowledge(newKnowledge string) {
b.Knowledge = newKnowledge
}