help with map[string] interfaces

polaris · 2015-04-07 10:57:31 · 2217 次点击    
这是一个分享于 2015-04-07 10:57:31 的资源,其中的信息可能已经有所发展或是发生改变。

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:

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.

kung-foo:

Thanks!

ItsNotMineISwear:

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.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

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