go - 是否有一种惯用的 Go 方法来干燥以下代码 :

标签 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
}

最佳答案

关于您可以嵌入的 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/

相关文章:

google-app-engine - 是否可以在 Google appengine 标准环境中使用 Gorilla mux 路由器?

go - 是否可以在处理时将项目添加到 Go channel ?

go - 解码yaml

go - 将 JSON 对象 "as is"存储到数据存储中

go - 为什么可以在 Go 的多个 return 语句中重新定义 err

http - 在浏览器选项卡中查询时如何保护 GET 请求

go - 为什么 Revel JSON 响应中的所有键都不大写?

ubuntu - 我试图杀死特定进程ID上的golang脚本但是当我杀死它时它说终止但仍在运行

go 例程未从 channel 收集所有对象

go - 如何在 slice 中连接多个管道命令