我無法找出在 Go 中使用接口的正確方法。我的函數需要獲取實現某種方法的項目的映射。它看起來像這樣:type foo interface { bar() string}func doSomething(items map[string]foo) {}我正在嘗試使用實現foo接口的類型調用此函數。type baz struct { }func (b baz) bar() string { return "hello"}items := map[string]baz{"a": baz{}}doSomething(items)但我收到以下錯誤:cannot use items (type map[string]baz) as type map[string]foo in function argument但是,當我這樣做時它工作正常:items := map[string]foo{"a": baz{}}doSomething(items)但是我想針對不同的接口重用這個相同的地圖?;旧衔艺谒饕芏鄬ο?,然后將它們傳遞給需要實現不同接口來計算結果的各種函數。我要地圖傳遞給一個函數作為地圖的一個foo和另一個功能地圖foobar。我嘗試了各種類型的斷言和轉換,但似乎沒有任何效果,所以我不確定我是沒有使用正確的語法還是完全錯誤。去游樂場http://play.golang.org/p/8mMWCDG7vm。
- 1 回答
- 0 關注
- 196 瀏覽
添加回答
舉報
0/150
提交
取消