<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>
