IsaIkari
IsaIkari

Reputation: 1154

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

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?

Upvotes: 0

Views: 41

Answers (1)

blackgreen
blackgreen

Reputation: 44647

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
}

Upvotes: 1

Related Questions