Go: Invalid Operation - Type *map[key]value Does Not Support Indexing
In Go, attempts to pass a map by pointer and modify the original map through the pointer may result in an "invalid operation" error. This is because indexing on a pointer to a map is not supported in Go.
To resolve this issue, it is necessary to index on the map itself rather than the pointer. Here's a modified code that demonstrates how to do this:
package main import "fmt" type Currency string type Amount struct { Currency Currency Value float32 } type Balance map[Currency]float32 func (b *Balance) Add(amount Amount) *Balance { current, ok := (*b)[amount.Currency] if ok { (*b)[amount.Currency] = current + amount.Value } else { (*b)[amount.Currency] = amount.Value } return b } func main() { b := &Balance{Currency("USD"): 100.0} b = b.Add(Amount{Currency: Currency("USD"), Value: 5.0}) fmt.Println("Balance: ", (*b)) }
By dereferencing the pointer to the map (*b) before indexing, the code now correctly modifies the original map.
Note: While the above code demonstrates how to modify a map through a pointer, it is generally more idiomatic to pass the map by value in Go. By passing a value, changes made to the map are automatically propagated back to the original map.
The above is the detailed content of Why Do I Get 'Invalid Operation - Type *map[key]value Does Not Support Indexing' in Go?. For more information, please follow other related articles on the PHP Chinese website!