What is the simplest way to expand a slice to its capacity?
"Extending" a slice to its capacity is simply a slice expression, and specify the capacity as the high index. The high index does not need to be less than the length. The restriction is:
For arrays or strings, the indices are in range if
0 <= low <= high <= len(a)
, otherwise they are out of range. For slices, the upper index bound is the slice capacitycap(a)
rather than the length.
Example:
b := make([]byte, 10, 20)
fmt.Println(len(b), cap(b), b)
b = b[:cap(b)]
fmt.Println(len(b), cap(b), b)
Output (try it on the Go Playground):
10 20 [0 0 0 0 0 0 0 0 0 0]
20 20 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
You can expand a slice to its capacity with slicing:
s = s[:cap(s)]