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.
Code
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
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.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 Filter Slices In Place print when run?
- Run it as a complete program — the output lines carry labels such as `kept:`, `len:`, `stale tail:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.