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

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”.

The error “invalid operation: type *map[key]value does not support indexing” in Go occurs when you are trying to access elements of a map using a pointer to the map instead of the map itself.

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.

Leave a Comment