Invalid Operation: Go's Perplexing Map Pointer Indexing
When manipulating maps in Go, one might encounter the error message: "invalid operation - type map[key]value does not support indexing." This error arises when attempting to index a map pointer (map[key]value) instead of the map value itself. Contrary to the norm with structs, dereferencing is not automated for maps.
The key to resolving this issue is to dereference the pointer to access the map value before performing indexing operations. Consider the following example:
func (b *Balance) Add(amount Amount) *Balance { // Dereference the pointer to access the map current, ok := (*b)[amount.Currency] if ok { (*b)[amount.Currency] = current + amount.Value } else { (*b)[amount.Currency] = amount.Value } return b }
In this scenario, the "map[key]value" is dereferenced using the "" operator to reveal the actual map value before indexing.
Go's pointer handling for maps differs from that of structs. To avoid excessive copying, it's not necessary to define receiver functions that take map pointers. Instead, pass the map value directly, as demonstrated in the original code snippet.
By understanding the subtle nuances of map pointers in Go, programmers can effectively resolve this enigmatic error message and confidently manipulate maps without the need for unnecessary value copying.
The above is the detailed content of Why Does Go Throw 'Invalid Operation - Type Map[key]value Does Not Support Indexing'?. For more information, please follow other related articles on the PHP Chinese website!