Middle+
Is it possible to use another map or slice as a key in a map?
sobes.tech AI
Answer from AI
In Go, the key in a map can only be types that support the comparison operation (operator ==). This means that using a map or slice as a key is not allowed because they are not compared by value.
If you need to use a composite key, you can:
- Use a string or another primitive type that is formed from the values of a map or slice (for example, serialize to JSON or use concatenation).
- Define your own structure with comparable fields and use it as a key.
Example using a structure as a key:
package main
import "fmt"
type Key struct {
ID int
Name string
}
func main() {
m := make(map[Key]string)
k := Key{ID: 1, Name: "test"}
m[k] = "value"
fmt.Println(m[k])
}
Thus, you cannot directly use a map or slice as a key, but you can work around this limitation using other approaches.