Clamp Capacity With slices.Clip
Trim a slice back to its length with slices.Clip so unused backing capacity cannot be appended into, and watch the next append allocate fresh storage.
Code
package main
import (
"fmt"
"slices"
)
func main() {
// 预留容量后只填了三个元素:len 3 / cap 8
base := make([]int, 0, 8)
base = append(base, 1, 2, 3)
fmt.Printf("before clip len=%d cap=%d\n", len(base), cap(base))
// Clip 把容量收敛到长度:未使用的那段容量不再可写
clipped := slices.Clip(base)
fmt.Printf("after clip len=%d cap=%d\n", len(clipped), cap(clipped))
// 关键差别:cap == len 后 append 必须另开数组,
// 因此改写新元素不会回头污染 base
grown := append(clipped, 4)
grown[0] = 99
fmt.Printf("grown len=%d cap=%d base[0]=%d\n", len(grown), cap(grown), base[0])
// 原切片未被修改,说明两个切片已经不共享可写区域
fmt.Println("base:", base)
}How it works
Clamp Capacity With slices.Clip reduces to the function main.
Caveats
- Self-contained — no imports beyond what the runtime already provides.
Using it
The one declaration doing the work: func main()
Each run prints the 4 labeled blocks before clip len=, after clip len=, grown len=, base: in source order.
Key statements
base = append(base, 1, 2, 3)
grown := append(clipped, 4)
base := make([]int, 0, 8)
Interactive Tools for This Topic
CSS clamp() GeneratorGenerate responsive clamp(MIN, PREFERRED, MAX) values with automatic calc() wrapping for expressions.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 Clamp Capacity With slices.Clip print when run?
- Running the file directly is enough — expect labeled output lines such as `before clip len=`, `after clip len=`, `grown len=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.