英文:
How to convert a map of two interfaces to a map of two structs
问题
如果我们有一个接口A和一个实现它的结构体a,并且有一个对象aobj,它的类型是接口A,我们可以使用aobj.(*a)进行转换。
然而,如果我有两个接口,比如A和B,以及对应的两个结构体a和b。我还有一个A到B的映射,即map[A]B。是否有一种类似的方式可以将map[A]B转换为map[a]b?
英文:
If we have an interface A and a struct a implementing it, and there's an object aobj which is of the type interface A, we can do the conversion with aobj.(*a).
However, if I have 2 interfaces, say A and B, and two corresponding struct, a and b. And I also have a map between A and B, i.e. map[A]B. Is there any similar conversion from a map[A]B to a map[a]b?
答案1
得分: 1
你必须遍历源映射并对键和值进行类型断言:
func assertMap(m map[A]B) map[a]b {
out := make(map[a]b, len(m))
for k, v := range m {
out[k.(a)] = v.(b)
}
return out
}
英文:
You have to range over the source map and type assert both key and value:
func assertMap(m map[A]B) map[a]b {
out := make(map[a]b, len(m))
for k, v := range m {
out[k.(a)] = v.(b)
}
return out
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论