go - 具体类型与返回类型上的接口(interface)不匹配

标签 go

我在玩 Go,发现一个我无法解决的问题。假设我有这样的代码:

// Imagine this is an external package for querying MySQL: I run a query 
// and it gives me back a struct with a method "Result" to get the result
// as a string
// I can NOT modify this code, since it is an external package
package bar

type MySQL struct {}

func (m *MySQL) RunQuery() *MySQLResult {
    return &MySQLResult{}
}

type MySQLResult struct {}

func (r *MySQLResult) Result() string {
    return "foo"
}

我导入包并开始使用它:

// I created a little runner to help me
func run(m *bar.MySQL) string {
    return m.RunQuery().Result()
}

func main() {
    m := &bar.MySQL{}
    fmt.Println(run(m)) // Prints "foo"
}

我真的很喜欢我的助手“运行”,但我想让它更慷慨:我不希望人们总是给我一个 MySQL 客户端。它可以是任何具有“RunQuery”和“Result”方法的东西。所以我尝试使用接口(interface):

type AnyDB interface {
    RunQuery() interface{ Result() string }
}

func run(m AnyDB) string {
    return m.RunQuery().Result()
}

遗憾的是,这不再编译。我收到此错误:

cannot use m (type *MySQL) as type AnyDB in argument to run:
    *MySQL does not implement AnyDB (wrong type for RunQuery method)
        have RunQuery() *MySQLResult
        want RunQuery() interface { Result() string }

这是 Go 不支持的,还是我做错了什么?

最佳答案

RunQuery 应该返回接口(interface),否则你总是要处理强类型。

AnyDB 不是必需的,我添加它是为了方便。

AnyResult 应在 bar 包中定义或导入其中。

type AnyDB interface {
    RunQuery() AnyResult
}

type MySQL struct{}

func (m *MySQL) RunQuery() AnyResult {
    return &MySQLResult{}
}

type AnyResult interface {
    Result() string
}

type MySQLResult struct{}

func (r *MySQLResult) Result() string {
    return "foo"
}

关于go - 具体类型与返回类型上的接口(interface)不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53661851/

相关文章:

macos - Golang TLS握手超时,影响go get和go代码

google-app-engine - dev_appserver 使用 goroot 1.6 而不是 1.8

google-app-engine - 您能解释一下应用程序引擎上下文接口(interface)是什么吗?

go - 处理上下文取消错误

go - 如何在golang中解决种族状况?

go - 指定用于在 Go 中查找的 DNS 服务器

database - golang 数据库更新一个不存在的条目

go - 防止在 Go 中为 Field-Only 结构重复函数

go - fmt 函数代表什么?

go - 卡夫卡服务器: Offset's topic has not yet been created