Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare a map parameter which accept any type of value in golang? [duplicate]

Tags:

generics

go

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

like image 282
Xiaochen Cui Avatar asked Jan 25 '26 15:01

Xiaochen Cui


1 Answers

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.

like image 148
for_stack Avatar answered Jan 28 '26 09:01

for_stack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!