我正在玩 Go,發(fā)現(xiàn)了一個(gè)我無(wú)法解決的問(wèn)題。假設(shè)我有這樣的代碼:// 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"}我導(dǎo)入了包并開(kāi)始使用它:// 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"}我真的很喜歡我的助手“運(yùn)行”,但我想讓它更慷慨:我不希望人們總是給我一個(gè) MySQL 客戶端。它可以是任何具有“RunQuery”和“Result”方法的東西。所以我嘗試使用接口:type AnyDB interface { RunQuery() interface{ Result() string }}func run(m AnyDB) string { return m.RunQuery().Result()}可悲的是,這不再編譯了。我收到此錯(cuò)誤: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 不支持的,還是我做錯(cuò)了什么?
1 回答

阿晨1998
TA貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊
RunQuery應(yīng)該返回接口,否則你總是要處理強(qiáng)類型。
AnyDB不是必需的,我添加它是為了方便。
AnyResult應(yīng)該在bar包中定義或?qū)肫渲小?/p>
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"
}
- 1 回答
- 0 關(guān)注
- 136 瀏覽
添加回答
舉報(bào)
0/150
提交
取消