Home >Backend Development >Golang >Why Can't I Take the Address of a Map Element in Go?
Why "Cannot Take the Address of Map Element"?
Consider the following code snippet:
odsMap := map[string]XMLElement{ "key": {Value: "value"}, } segRef := "key"
The following statement works:
x := odsMap[segRef] x.GetValue("@OriginDestinationKey")
However, this statement fails with the following errors:
cannot call pointer method on odsMap[segRef] cannot take the address of odsMap[segRef]
These errors occur because map index expressions are not addressable. The internal structure of a map may change when a new entry is added, preventing its address from being taken.
Therefore, when accessing a method with a pointer receiver on a non-pointer value stored in a map, an intermediate variable is required to take the address of that value, as seen in the working example.
To avoid this issue, consider storing pointer values in the map instead. For instance:
type My int func (m *My) Str() string { return strconv.Itoa(int(*m)) } odsMap := map[string]*My{} my := My(12) odsMap[segRef] = &my
Alternatively, you can assign the non-pointer value to a local variable and take its address:
x := odsMap[segRef] x.GetValue("@OriginDestinationKey") // Method call on *XMLElement
In conclusion, map index expressions are not addressable, necessitating the use of intermediate variables or alternative storage strategies when accessing pointer methods on non-pointer values in maps.
The above is the detailed content of Why Can't I Take the Address of a Map Element in Go?. For more information, please follow other related articles on the PHP Chinese website!