Grow Preallocates Slice Capacity
Reserve capacity for upcoming appends with slices.Grow so bulk inserts stop reallocating, and compare against the repeatedly-growing baseline.
Code
package main
import (
"fmt"
"slices"
)
func main() {
src := []int{1, 2, 3}
// Grow 保证容量至少再容纳 n 个元素:随后的 append 不再触发重新分配
grown := slices.Grow(src, 1000)
fmt.Println("room after grow:", cap(grown)-len(grown) >= 1000)
// 复用扩好的容量连续追加
total := append(grown, 4, 5, 6)
fmt.Println("len:", len(total))
// 对照:从零开始的 append 会随增长多次扩容搬移
slow := []int{}
for i := 0; i < 1000; i++ {
slow = append(slow, i)
}
fmt.Println("slow filled:", len(slow) == 1000, "cap sufficient:", cap(slow) >= 1000)
}Inside the snippet
Count the function main as the entire surface area of Grow Preallocates Slice Capacity.
The one repetition in this snippet is the loop for i := 0; i < 1000; i++.
Putting it to use
The demo output is labeled (room after grow:, len:, slow filled:), so the output doubles as a step-by-step trace of what the file did.
Core lines
total := append(grown, 4, 5, 6)
slow = append(slow, i)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Grow Preallocates Slice Capacity print when run?
- Run it as a complete program — the output lines carry labels such as `room after grow:`, `len:`, `slow filled:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.