Sobes.tech
Junior — Middle

What are the limitations and features of using keys in a map data structure?

sobes.tech AI

Answer from AI

In Go, keys in a map must satisfy certain requirements:

  • The key must be comparable: This means the key type must support the comparison operations == and !=. For example, basic types (int, string, bool), pointers, structs, and arrays if all their fields are comparable.

  • Slices, maps, and functions cannot be used as keys: These types are not comparable and will cause a compile-time error.

  • Features:

    • Structs can be keys if all their fields are comparable.
    • If a struct contains a slice or map field, it cannot be a key.
  • Performance: Using large structs as keys can be inefficient due to copying.

Example:

m := make(map[string]int) // string is a valid key

// Invalid key:
// m2 := make(map[[]int]string) // compile error

// Struct with comparable fields:
 type Point struct { X, Y int }
 m3 := make(map[Point]string)
 m3[Point{1,2}] = "A"

Thus, when choosing a key, it is important to consider its comparability and immutability.