Go 具体类型与返回类型上的接口不匹配
我在玩围棋,发现了一个我无法解决的问题。假设我的代码如下所示:Go 具体类型与返回类型上的接口不匹配,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
// 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"
}
我真的很喜欢我的助手“run”,但我想让它更慷慨一些:我不希望人们总是给我一个MySQL客户端。它可以是任何具有“RunQuery”和“Result”方法的对象。因此,我尝试使用接口:
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
应该返回接口,否则您必须始终处理强类型
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"
}
RunQuery
应该返回接口,否则您必须始终处理强类型
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"
}
我无法更改“MySQL”库。这是我从GitHub获得的一个外部包。不幸的是,他们没有返回接口-他们返回的是一个具体类型。在这种情况下,你必须接受
MySQLResult
。这很不幸:(谢谢你的回答!我不能更改“MySQL”库。这是我从GitHub获得的一个外部包。遗憾的是,它们没有返回接口-它们返回的是一个具体类型。在这种情况下,您必须使用MySQLResult
。这很不幸:(感谢您的回答!错误非常清楚地告诉您问题所在-RunQuery
方法返回了错误的类型。我的问题不是编译器在说什么,而是编译器为什么这么说。如果您仔细看,我制作的接口应该准确地描述方法的行为。当然,但您不是不返回接口,所以这无关紧要。这就是我要问的:返回的结构与接口匹配,但Go仍然不会接受它。我想知道我在接口的实现中是否遗漏了什么,或者它实际上是Go不支持的。找到答案:错误非常清楚地告诉您问题所在是--yourRunQuery
方法返回了错误的类型。我的问题不是编译器在说什么,而是编译器为什么这么说。如果仔细看,我创建的接口应该准确地描述方法的行为。当然,但是你没有返回接口,所以这与此无关。这就是我要问的:struct返回的与接口匹配,但Go仍然不会接受它。我想知道我的接口实现中是否遗漏了某些内容,或者它实际上是Go不支持的内容。找到了答案: