Unexpected Pointer Behavior in range
Loop Over Maps in Go (Go 1.24.1)
#73138
Labels
BugReport
Issues describing a possible bug in the Go implementation.
Go version
1.24.1
Output of
go env
in your module/workspace:What did you do?
I'm encountering unexpected behavior when iterating over a map in Go 1.24.1, where pointers to map values inside a
range
loop do not behave consistently across different environments. The issue manifests as the pointers either referring to the same object (the last item in the loop) or different items, depending on the platform.Code Example:
What did you see happen?
What did you expect to see?
I know that the Go
range
loop over maps reuses the same variable for each iteration, which can lead to unexpected behavior when taking pointers to the map values. This happens because the memory foritem
is reused across iterations, causing all pointers to potentially reference the same underlying object (the last one processed).The issue can be resolved by explicitly creating a copy of the
item
inside the loop:Nevertheless I am highly surprised that I see different outcome using different or even the same go version (1.24.1) dependent on the actual environments.
Request for Clarification:
Thanks for your support!
The text was updated successfully, but these errors were encountered: