I have a function:
func ReturnTuples(map_ map[interface{}]interface{}) [][]interface{} {
In which I'm trying to call like this:
m := make(map[string]int)
m["k1"] = 7
m["k2"] = 13
fmt.Println(ReturnTuples(m))
But I'm getting
cannot use m (type map[string]int) as type map[interface {}]interface {} in argument to ReturnTuples
Shouldn't it work since string
and int
both implement interface{}
?
I've searched and the best I could find was Convert map[interface {}]interface {} to map[string]string but it won't answer why I cannot use m
as an argument.
I also believe that if the argument of the function were only interface{}
it would work too, since map[something][something]
implements interface
, right? What is the best way to do it, and why it won't work in my case?
A solution to your problem, simply initiate the map as an empty interface of empty interfaces:
m := map[interface{}]interface{}
then you can assign any type key or value you want in the 'ReturnTuples' function.
NOTE: remember that if you want to use the values later as the original types, you will need to use type assertion because now they are of type interface{}
You may do something this like this, were anything
is one map value which you can get using a for loop:
switch v := anything.(type) {
case string:
fmt.Println(v)
case int32, int64:
fmt.Println(v)
case string:
fmt.Println(v)
case SomeCustomType:
fmt.Println(v)
default:
fmt.Println("unknown")
}
If you are looking for an explanation for the "why" @ymonad gave a full answer so I wont repeat it again.
hope it make sense
PS: don't get the down votes on the question, a legit one in my eyes...
You can type assert in the function itself.
func test(m interface{},key interface{}) bool { // Map is passed as reference
ma := m.(map[interface{}]interface{})
if _, ok := ma[key]; ok == false {
....
}