Home > Software design >  How to use interface with map in Golang?
How to use interface with map in Golang?

Time:12-09

I have a struct which implements an interface - hence I can assign that struct to a variable of said interface.

But I'd like to create a type which maps from string -> Whoa interface, but to be able to use a concrete struct when initializing. This doesn't work, I'm getting:

cannot use (map[string]Boom literal) (value of type map[string]Boom) as poppa value in variable declaration

Any help appreciated!

package main

type Whoa interface {
    yes()
}

type Boom struct {
    hey string
}

func (b Boom) yes() {

}

type poppa map[string]Whoa

func main() {
    var thisWorks Whoa = Boom{}
    var thisDoesnt poppa = map[string]Boom{}
}

CodePudding user response:

    var thisWorks Whoa = Boom{}

That works because Boom{} implements Whoa.

You might think since Boom implements Whoa, then map[string]Boom can also be a map[string]Whoa. But it cannot.

What you can do is create a map[string]Whoa whose values are Boom{}s.

    var thisShould poppa = map[string]Whoa{"first": Boom{}}

The moral of the story is, slices and maps of interface types may hold any value that satisfies that interface, but slices and maps of types that satisfy an interface are not equivalent to slices and maps of that interface.

Write code to copy the map[string]Boom{} to a poppa

If you had a map[string]Boom that you wanted to turn into a map[string]Whoa, the right way to do it is something like:

whoas := make(map[string]Whoa)
for k, v := map[string]Boom{} {
  whoas[k] = v
}
  • Related