Hi all, I am struggling to figure out how to use a map[string]*SomeType
as a parameter to a function that takes a map[string]SomeInterface
(where SomeType
implements SomeInterface
). Any ideas? Is this a limitation of go's map?
The following code results in:
main.go:35: cannot use f (type map[string]*Foo) as type map[string]Hashable in argument to hash
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)
}
https://play.golang.org/p/mNirwiHhrl
评论:
Ainar-G:
kung-foo:It's in the FAQ. Although the FAQ entry is about slices, it's basically the same with maps. In your example you can do this:
func main() { f := make(map[string]Hashable, 1) f["yup"] = &Foo{} hash(f) }
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.
ItsNotMineISwear:Thanks!
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.