Skip to content

Commit d3e827d

Browse files
Deleplacegopherbot
authored andcommitted
slices: Delete clears the tail when j == len(s)
Fixes #65669 Change-Id: Ifd2011dd604fef399e4352b804fc2f6a9e74096e Reviewed-on: https://go-review.googlesource.com/c/go/+/566237 Reviewed-by: Ian Lance Taylor <[email protected]> Reviewed-by: Keith Randall <[email protected]> Auto-Submit: Keith Randall <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Keith Randall <[email protected]>
1 parent b847d4c commit d3e827d

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/slices/slices.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,11 @@ func Replace[S ~[]E, E any](s S, i, j int, v ...E) S {
258258
return Insert(s, i, v...)
259259
}
260260
if j == len(s) {
261-
return append(s[:i], v...)
261+
s2 := append(s[:i], v...)
262+
if len(s2) < len(s) {
263+
clear(s[len(s2):len(s)]) // zero/nil out the obsolete elements, for GC
264+
}
265+
return s2
262266
}
263267

264268
tot := len(s[:i]) + len(v) + len(s[j:])

src/slices/slices_test.go

+13
Original file line numberDiff line numberDiff line change
@@ -1120,6 +1120,19 @@ func TestReplaceOverlap(t *testing.T) {
11201120
}
11211121
}
11221122

1123+
func TestReplaceEndClearTail(t *testing.T) {
1124+
s := []int{11, 22, 33}
1125+
v := []int{99}
1126+
// case when j == len(s)
1127+
i, j := 1, 3
1128+
s = Replace(s, i, j, v...)
1129+
1130+
x := s[:3][2]
1131+
if want := 0; x != want {
1132+
t.Errorf("TestReplaceEndClearTail: obsolete element is %d, want %d", x, want)
1133+
}
1134+
}
1135+
11231136
func BenchmarkReplace(b *testing.B) {
11241137
cases := []struct {
11251138
name string

0 commit comments

Comments
 (0)