Passing Maps by Value vs. Pointer in Go
In Go, passing by value and by pointer can be confusing, especially when dealing with map types. This article addresses the issue of indexing a map passed by pointer, which leads to compilation errors.
The Problem
When attempting to pass a map by pointer and modify its values, Go raises an error that the type does not support indexing. This is because indexing on a pointer is not supported for maps.
The Solution
To avoid this error, dereference the pointer before indexing the map. Instead of b[amount.Currency], use (*b)[amount.Currency].
Further Discussion
By default, simple types like integers are passed by value, while structs and interfaces are passed by reference. However, this is not the case for maps. Maps are passed by reference by default, so passing them by value or pointer is essentially the same.
In the example above, using a pointer receiver for the Add method is unnecessary because the map is already passed by reference. The method could be written as follows without any loss of functionality:
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 }
In summary, when working with maps, it is not necessary to pass them by pointer to avoid copying. Passing by value achieves the same result without the need for dereferencing.
The above is the detailed content of Why Does Indexing a Map Passed by Pointer in Go Cause Compilation Errors?. For more information, please follow other related articles on the PHP Chinese website!