Jay Taylor's notes

back to listing index

golang/go

[web search]
Original source (github.com)
Tags: golang go slice github.com
Clipped on: 2017-04-05

Additional Tricks

Filtering without allocating

This trick uses the fact that a slice shares the same backing array and capacity as the original, so the storage is reused for the filtered slice. Of course, the original contents are modified.

b := a[:0]
for _, x := range a {
	if f(x) {
		b = append(b, x)
	}
}