diff --git a/src/sync/map.go b/src/sync/map.go index e8ccf58b56b34b..00b2446153c33e 100644 --- a/src/sync/map.go +++ b/src/sync/map.go @@ -461,7 +461,8 @@ func (m *Map) Range(f func(key, value any) bool) { read = m.loadReadOnly() if read.amended { read = readOnly{m: m.dirty} - m.read.Store(&read) + copyRead := read + m.read.Store(©Read) m.dirty = nil m.misses = 0 } diff --git a/src/sync/map_test.go b/src/sync/map_test.go index 1eb3fc68a5330d..20872f3b72ba44 100644 --- a/src/sync/map_test.go +++ b/src/sync/map_test.go @@ -5,6 +5,7 @@ package sync_test import ( + "internal/testenv" "math/rand" "reflect" "runtime" @@ -280,3 +281,16 @@ func TestCompareAndSwap_NonExistingKey(t *testing.T) { t.Fatalf("CompareAndSwap on an non-existing key succeeded") } } + +func TestMapRangeNoAllocations(t *testing.T) { // Issue 62404 + testenv.SkipIfOptimizationOff(t) + var m sync.Map + allocs := testing.AllocsPerRun(10, func() { + m.Range(func(key, value any) bool { + return true + }) + }) + if allocs > 0 { + t.Errorf("AllocsPerRun of m.Range = %v; want 0", allocs) + } +}