【发布时间】:2014-04-03 00:56:25
【问题描述】:
我无法找出在 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 的地图传递。
我尝试了各种类型断言和转换,但似乎没有任何效果,所以我不确定我只是没有使用正确的语法还是完全错误。
【问题讨论】: