具体类型与返回类型上的接口不匹配 [英] Concrete type does not match interface on return type

查看:54
本文介绍了具体类型与返回类型上的接口不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am playing around with Go and found a problem I can't get around. Suppose I have my code like this:

// 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 imported the package and started to use it:

// 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"方法的任何东西.所以我尝试使用接口:

I really like my helper "run", but I'd like to make it more generous: I don't expect people to always pass me a MySQL client. It could be anything that has a "RunQuery" and "Result" method. So I try to use interfaces:

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

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

可悲的是,它不再编译了.我收到此错误:

Sadly, this doesn't compile anymore. I get this error:

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不支持此操作吗,还是我做错了什么?

Is this not supported by Go, or am I doing something wrong?

推荐答案

RunQuery 应该返回接口,否则您始终必须处理强类型.

RunQuery should return interface, otherwise you always have to deal with strong type.

AnyDB 不是必需的,我为了方便起见添加了它.

AnyDB is not required, I added it for connivence.

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

AnyResult should be defined in bar package or being imported into it.

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"
}

这篇关于具体类型与返回类型上的接口不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆