Skip to content

Commit

Permalink
slices: document two oddities
Browse files Browse the repository at this point in the history
Fixes #70935

Change-Id: Idf4a38a05ba595d616b6469a14419ff873bbd354
Reviewed-on: https://go-review.googlesource.com/c/go/+/638095
Reviewed-by: Keith Randall <khr@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Keith Randall <khr@google.com>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
  • Loading branch information
adonovan committed Dec 21, 2024
1 parent 669d87a commit 110ab1a
Showing 1 changed file with 4 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/slices/slices.go
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,7 @@ func Grow[S ~[]E, E any](s S, n int) S {
panic("cannot be negative")
}
if n -= cap(s) - len(s); n > 0 {
// This expression allocates only once (see test).
s = append(s[:cap(s)], make([]E, n)...)[:len(s)]
}
return s
Expand Down Expand Up @@ -483,6 +484,9 @@ func Concat[S ~[]E, E any](slices ...S) S {
panic("len out of range")
}
}
// Use Grow, not make, to round up to the size class:
// the extra space is otherwise unused and helps
// callers that append a few elements to the result.
newslice := Grow[S](nil, size)
for _, s := range slices {
newslice = append(newslice, s...)
Expand Down

0 comments on commit 110ab1a

Please sign in to comment.