go - 为什么 golang duck typing 在我下面的代码中对我不起作用?

标签 go

在下面的代码中,我尝试创建模型接口(interface)和 API 接口(interface)的具体实现:

package main

import "fmt"

/////////

type Model interface {
    ID() string
}

type API interface {
    Create(Model)
}

/////////

type ConcreteModel struct {}

func (model ConcreteModel) ID() string {
    return "123"
}

func (model ConcreteModel) Name() string {
    return "aron"
}

type ConcreteAPI struct{}

func (api ConcreteAPI) Create(model ConcreteModel) {
    fmt.Println("Created concrete model with id " + model.ID() + ", name " + model.Name())
}

func main() {
    // invocation via interface
    func(api API) {
        api.Create(ConcreteModel{})
    }(ConcreteAPI{})
}

令我非常困惑的是为什么我在运行这段代码时会收到以下错误:

ConcreteAPI does not implement API (wrong type for Create method)
        have Create(ConcreteModel)
        want Create(Model)

根据我对 golang ducktyping 的了解,ConcreteAPI 似乎应该履行 Create(Model) 的契约,因为 ConcreteModel 具有 Model 所需的方法,即ID() 字符串

我想尝试做这样的事情的原因是 func(api API) 是知道如何使用具体 API 实现的东西的替代品,在我预期的真实中 -世界代码库。

有人对如何使上述内容真正起作用有什么建议吗?

最佳答案

ConcreteAPI没有实现API的方法,请您添加:

func( concreteApi *ConcreteAPI ) 创建(模型){}

但是您还有另一个错误,请参阅下面的详细信息: ConcreteModel 也没有实现 Model

关于go - 为什么 golang duck typing 在我下面的代码中对我不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41713767/

相关文章:

opencv - 在 ARM Docker 容器中构建 OPENCV 时出现问题

golang 从打印默认值中标记隐藏选项

go - 对接口(interface)实现和调用的这些代码感到迷惑?

json - 如何在Go中显示来自API的JSON响应?

rest - golang gin-gonic 和包中的拆分文件

go - 子文件夹中的调用函数

macos - 在 MacOS 上使用 Go 1.5 创建 RAW 数据包

ssl - 使用自签名 SSL 证书

go - 如何使用虚拟属性

go - 无法使用 if val 从 Golang 中的 map[time.Time]Measure 获取值,ok := mapMeasures[ts]; ok {}