Sobes.tech
Junior — Middle

Can a Map use another Map as a key?

sobes.tech AI

Answer from AI

In Go, the key in a map can only be a type that supports the comparison operation (operator ==). The built-in map type does not support comparison, so a map cannot be used as a key in another map.

If you need to use a complex composite key, you can:

  • Use a struct with comparable fields (e.g., strings, numbers).
  • Serialize the map into a string (e.g., JSON) and use that string as the key.

Example of using a struct as a key:

Type Key struct {
    Field1 string
    Field2 int
}

m := make(map[Key]string)
m[Key{Field1: "a", Field2: 1}] = "value"

Thus, you cannot directly use a map as a key.

Can a Map use another Map as a key? — Golang - sobes.tech