Skip to content

Commit

Permalink
slices: preserve nil/non-nil in Clone
Browse files Browse the repository at this point in the history
Fixes golang/go#49660

Change-Id: I2bc371fed2193293509573d8994c94775edcf25e
Reviewed-on: https://go-review.googlesource.com/c/exp/+/365174
Trust: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Robert Griesemer <gri@golang.org>
  • Loading branch information
ianlancetaylor committed Nov 18, 2021
1 parent 03df57b commit eb295bb
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
6 changes: 5 additions & 1 deletion slices/slices.go
Expand Up @@ -156,7 +156,11 @@ func Delete[S ~[]E, E any](s S, i, j int) S {
// Clone returns a copy of the slice.
// The elements are copied using assignment, so this is a shallow clone.
func Clone[S ~[]E, E any](s S) S {
return append(S(nil), s...)
// Preserve nil in case it matters.
if s == nil {
return nil
}
return append(S([]E{}), s...)
}

// Compact replaces consecutive runs of equal elements with a single copy.
Expand Down
6 changes: 6 additions & 0 deletions slices/slices_test.go
Expand Up @@ -457,6 +457,12 @@ func TestClone(t *testing.T) {
if !Equal(s2, want) {
t.Errorf("Clone(%v) changed unexpectedly to %v", want, s2)
}
if got := Clone([]int(nil)); got != nil {
t.Errorf("Clone(nil) = %#v, want nil", got)
}
if got := Clone(s1[:0]); got == nil || len(got) != 0 {
t.Errorf("Clone(%v) = %#v, want %#v", s1[:0], got, s1[:0])
}
}

var compactTests = []struct {
Expand Down

0 comments on commit eb295bb

Please sign in to comment.