help with map[string] interfaces

polaris · · 1907 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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&#39;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 &#34;fmt&#34; type Hashable interface { HashCode() string } type Foo struct { Hashable } func (f *Foo) HashCode() string { return &#34;I&#39;m a foo&#34; } func hash(stuff map[string]Hashable) { for k, v := range stuff { fmt.Printf(&#34;%s %s\n&#34;, k, v.HashCode()) } } func main() { f := make(map[string]*Foo, 1) f[&#34;yup&#34;] = &amp;Foo{} hash(f) } </code></pre> <p><a href=""></a></p> <hr/>**评论:**<br/><br/>Ainar-G: <pre><p>It&#39;s in the <a href="">FAQ</a>. Although the FAQ entry is about slices, it&#39;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[&#34;yup&#34;] = &amp;Foo{} hash(f) } </code></pre> <p>If you already have a map, you&#39;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&#39;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

1907 次点击  
加入收藏 微博
0 回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传