接口中具体类型与返回类型不匹配
时间:2024-03-06
浏览:410
作者:佚名
在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《接口中具体类型与返回类型不匹配》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!
问题内容
我正在使用 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"
}
我真的很喜欢我的助手“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"
}文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《接口中具体类型与返回类型不匹配》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.28
11.28
11.28
11.28
热门专题
