How to Fix Go: invalid operation – type *map[key]value does not support indexing

The error invalid operation: type *map[key]value does not support indexing in Go occurs when you try to “use indexing on a variable that does not support it.”

To fix the invalid operation: type *map[key]value does not support indexing error in Golang, you need to “dereference the pointer to the map before using indexing”.

Reproduce the error

package main

import (
  "fmt"
)

func main() {
  myMap := make(map[string]int)
  myMap["one"] = 1
  myMap["two"] = 2

  pointerToMap := &myMap

  // The following line causes an error
  fmt.Println("Value for key 'one':", pointerToMap["one"])
}

Output

invalid operation: cannot index pointerToMap (variable of type *map[string]int)

Fixed code

package main

import (
  "fmt"
)

func main() {
  myMap := make(map[string]int)
  myMap["one"] = 1
  myMap["two"] = 2

  pointerToMap := &myMap

  // Dereference the pointer before indexing
  fmt.Println("Value for key 'one':", (*pointerToMap)["one"])
}

Output

Value for key 'one': 1

In this fixed code, we dereferenced the pointer to the map using (*pointerToMap) before accessing the element with the key “one”.

Remember to “dereference the pointer to the map before using indexing” to access its elements.

That’s it!