Choose comparable map keys
Choose comparable map keys
Map keys must be comparable with == and !=. Strings, integers and arrays of comparable elements are valid keys. Slices, maps and functions cannot be key types. Values have no such restriction.
package main
import "fmt"
func main() { m := map[[2]int]string{} m[[2]int{1, 2}] = "seat A" m[[2]int{2, 1}] = "seat B" fmt.Println(m[[2]int{1, 2}], m[[2]int{2, 1}], len(m))}An array key compares its elements in order. The two coordinate pairs are distinct. A slice cannot replace the array as a key even if it has exactly two elements.
Expected output:
seat A seat B 2Use slices as values
package main
import "fmt"
func main() { m := map[string][]int{} m["A"] = []int{2, 4} m["B"] = []int{6} fmt.Println(m["A"], m["B"])}A string key is comparable; its slice value need not be. Later chapters cover structs and interfaces: struct keys require comparable fields, and an interface key can panic if its dynamic value is not comparable. Avoid floating-point NaN keys because NaN does not equal itself.
Expected output:
[2 4] [6]Try it locally
Use [2]int keys to store 10 and 20 at coordinates {0,1} and {1,0}. Print both values and length.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Maps 05: Choose comparable map keys
Check the lesson objective before moving on.
Which is a valid key type?
Is map[string][]int valid?