Filter Slices In Place

Filter a slice into its own backing array with s[:0] and append, then prove the aliasing by reading the stale tail beyond the truncated length.

GoData Integrity

Code

gosnippet
22 lines
package main

import "fmt"

func main() {
	readings := []int{12, 0, 98, 0, 45, 0, 7}

	// filter the slice in place: dst shares the backing array of readings
	dst := readings[:0]
	for _, v := range readings {
		if v != 0 {
			dst = append(dst, v)
		}
	}
	readings = dst

	fmt.Println("kept:", readings)
	fmt.Println("len:", len(readings), "cap:", cap(readings))

	// 截短后的槽位仍残留旧值:底层数组被原切片视图共享
	fmt.Println("stale tail:", readings[:7])
}

Inside the snippet

Count the function main as the entire surface area of Filter Slices In Place.

Iteration happens inside for _, v := range readings — everything outside it runs once.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Running the file prints labeled results such as kept:, len:, stale tail: — each operation’s effect is visible in the output.

Core lines

for _, v := range readings {
if v != 0 {
dst = append(dst, v)
}
}

Interactive Tools for This Topic

FAQ

What does Filter Slices In Place print when run?
Run it as a complete program — the output lines carry labels such as `kept:`, `len:`, `stale tail:`.