diff --git a/src/slices/slices.go b/src/slices/slices.go index b0f048a6566..3e01eb2fb77 100644 --- a/src/slices/slices.go +++ b/src/slices/slices.go @@ -258,7 +258,11 @@ func Replace[S ~[]E, E any](s S, i, j int, v ...E) S { return Insert(s, i, v...) } if j == len(s) { - return append(s[:i], v...) + s2 := append(s[:i], v...) + if len(s2) < len(s) { + clear(s[len(s2):len(s)]) // zero/nil out the obsolete elements, for GC + } + return s2 } tot := len(s[:i]) + len(v) + len(s[j:]) diff --git a/src/slices/slices_test.go b/src/slices/slices_test.go index 31d59abe17b..4b5f0355df2 100644 --- a/src/slices/slices_test.go +++ b/src/slices/slices_test.go @@ -1120,6 +1120,19 @@ func TestReplaceOverlap(t *testing.T) { } } +func TestReplaceEndClearTail(t *testing.T) { + s := []int{11, 22, 33} + v := []int{99} + // case when j == len(s) + i, j := 1, 3 + s = Replace(s, i, j, v...) + + x := s[:3][2] + if want := 0; x != want { + t.Errorf("TestReplaceEndClearTail: obsolete element is %d, want %d", x, want) + } +} + func BenchmarkReplace(b *testing.B) { cases := []struct { name string