3

For your convenience: go playground

I has a function which does not care the value type of a map parameter, so I declare it as this:

func foo(generalMap map[string]interface{}) {}

But when I call it with a specified map like this:

myMap := make(map[string]Bar)
foo(myMap)

Then the compiler error comes out: cannot use myMap (type map[string]Bar) as type map[string]interface {} in argument to foo

Xiaochen Cui
  • 2,337
  • 2
  • 13
  • 13
  • 2
    Soon (in Go 1.18), you'll be able to write such a generic function: `func foo[V any](generalMap map[string]V) { /* ... */ }`. – jub0bs Jun 12 '21 at 09:22

1 Answers1

7

You CANNOT do that. map[string]interface{} and map[string]Bar are two different types. You have to build a map[string]interface{} with the map[string]Bar manually.

mapAny := make(map[string]interface{})
for key, val := range myMap {
    mapAny[key] = val
}
foo(mapAny)

What you need is template in C++, however, Golang doesn't have template support.

for_stack
  • 21,012
  • 4
  • 35
  • 48
  • 5
    Hello from the future, It's ~March 2022, and we now have go-1.18. To anybody reading this, you may now use type aliases, like this: `map[string]any`. Where `any` is a type alias for `interface{}`. Have a great day! – masta Mar 29 '22 at 17:49