]> Cypherpunks repositories - gostls13.git/commitdiff
slices: simplify Clone a bit
authorBrad Fitzpatrick <bradfitz@golang.org>
Sat, 19 Aug 2023 16:08:38 +0000 (09:08 -0700)
committerBrad Fitzpatrick <bradfitz@golang.org>
Sun, 20 Aug 2023 04:12:09 +0000 (04:12 +0000)
No need for an explicit nil check. Slicing the input slice
down to zero capacity also preserves nil.

Change-Id: I1f53cc485373d0e65971cd87b6243650ac72612c
Reviewed-on: https://go-review.googlesource.com/c/go/+/521037
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
src/slices/slices.go

index a4d9f7e3f5ff3daebb44fa40d582ed3adfc3c659..252a8eecfc9f90bb1079b420ac8175e30b926b2b 100644 (file)
@@ -333,11 +333,8 @@ func Replace[S ~[]E, E any](s S, i, j int, v ...E) 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 {
-       // Preserve nil in case it matters.
-       if s == nil {
-               return nil
-       }
-       return append(S([]E{}), s...)
+       // The s[:0:0] preserves nil in case it matters.
+       return append(s[:0:0], s...)
 }
 
 // Compact replaces consecutive runs of equal elements with a single copy.