亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

具體類型與返回類型上的接口不匹配

具體類型與返回類型上的接口不匹配

Go
吃雞游戲 2023-05-15 14:43:41
我正在玩 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 packagepackage bartype 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 mefunc run(m *bar.MySQL) string {    return m.RunQuery().Result()}func main() {    m := &bar.MySQL{}    fmt.Println(run(m)) // Prints "foo"}我真的很喜歡我的助手“運行”,但我想讓它更慷慨:我不希望人們總是給我一個 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 不支持的,還是我做錯了什么?
查看完整描述

1 回答

?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

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"

}


查看完整回答
反對 回復 2023-05-15
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號