例如,我似乎在重复说话功能。
还有没有办法将婴儿和人类的初始知识移动到默认构造函数,而不是在创建新婴儿和人类时被传递?
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
}
最佳答案
关于您可以嵌入的 speak() 函数
type Knowledge string
func (b Knowledge) speak() {
fmt.Println(b)
}
type Baby struct {
Knowledge
}
type Human struct {
Knowledge
}
关于构造函数,对于这样一个简单的类型,buitin new() 似乎是可以的,但你可以编写一个初始化器
func Ini(k Knowledgable) {
switch k.(type) {
case *Baby:
k.changeKnowledge("ga-ga")
case *Human:
k.changeKnowledge("good things")
}
}
然后事情就成了
h := new(Human)
b:=new(Baby)
Ini(h)
Ini(b)
h.speak()
关于go - 是否有一种惯用的 Go 方法来干燥以下代码 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39420773/