如何将两个接口的映射转换为两个结构体的映射?

huangapple go评论83阅读模式
英文:

How to convert a map of two interfaces to a map of two structs

问题

如果我们有一个接口A和一个实现它的结构体a,并且有一个对象aobj,它的类型是接口A,我们可以使用aobj.(*a)进行转换。

然而,如果我有两个接口,比如AB,以及对应的两个结构体ab。我还有一个AB的映射,即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
}

huangapple
  • 本文由 发表于 2022年7月13日 04:45:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/72958183.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定