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.

GoData Integrity

Code

gosnippet
26 lines
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

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=`.