-1

In my function I was receiving an argument that contained a map for which the value's type was any. I would have thought that any type could therefore be sent, but I got the following error when I tired to use map[string]CustomStruct:

cannot use mapToPrint (variable of type map[string]CustomStruct) as type map[string]any in argument to printMap.

If I create the map with type's value any, everything works, including the assignment of CustomStruct to map values.

Here is a reproducing example:

type CustomStruct struct {
    name string
}

func main() {
    mapToPrint := make(map[string]CustomStruct, 0)
    mapToPrint["a"] = CustomStruct{"a"}
    mapToPrint["b"] = CustomStruct{"b"}
    printMap(mapToPrint)
}

func printMap(mapToPrint map[string]any) {
    for key, value := range mapToPrint {
        fmt.Println(key, value)
    }
}

go.dev

Marko
  • 733
  • 8
  • 21

1 Answers1

-1

As the go FAQ says here: It is disallowed by the language specification because the two types do not have the same representation in memory.

As the FAQ suggests, simply copy the data from your map into a map with value type any, and send it like so to the function:

printableMap := make(map[string]any, len(mapToPrint))
for key, value := range mapToPrint {
    printableMap[key] = value
}
Marko
  • 733
  • 8
  • 21