<p>Hi all, I am struggling to figure out how to use a <code>map[string]*SomeType</code> as a parameter to a function that takes a <code>map[string]SomeInterface</code> (where <code>SomeType</code> implements <code>SomeInterface</code>). Any ideas? Is this a limitation of go's map?</p>
<p>The following code results in:
<code>main.go:35: cannot use f (type map[string]*Foo) as type map[string]Hashable in argument to hash</code></p>
<pre><code>package main
import "fmt"
type Hashable interface {
HashCode() string
}
type Foo struct {
Hashable
}
func (f *Foo) HashCode() string {
return "I'm a foo"
}
func hash(stuff map[string]Hashable) {
for k, v := range stuff {
fmt.Printf("%s %s\n", k, v.HashCode())
}
}
func main() {
f := make(map[string]*Foo, 1)
f["yup"] = &Foo{}
hash(f)
}
</code></pre>
<p><a href="https://play.golang.org/p/mNirwiHhrl">https://play.golang.org/p/mNirwiHhrl</a></p>
<hr/>**评论:**<br/><br/>Ainar-G: <pre><p>It's in the <a href="http://golang.org/doc/faq#convert_slice_of_interface">FAQ</a>. Although the FAQ entry is about slices, it's basically the same with maps. In your example you can do this:</p>
<pre><code>func main() {
f := make(map[string]Hashable, 1)
f["yup"] = &Foo{}
hash(f)
}
</code></pre>
<p>If you already have a map, you'll have to convert all of its elements in a loop, because pointers and interface values are stored differently.</p></pre>kung-foo: <pre><p>Thanks!</p></pre>ItsNotMineISwear: <pre><p>Go's built in generic collections are not covariant. I remember reading some google group discussions of the implementation details that make it unlikely to change as well. </p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传