0 day streak
go / intermediate
Snippet

In-Place Slice Filtering to Optimize Memory Allocation

To filter elements in a slice without allocating a new backing array, you can perform an in-place filter. By maintaining an index n of valid items, you overwrite elements sequentially in the same slice. Finally, slicing the original slice up to n (numbers[:n]) returns the filtered view, optimizing memory usage and performance.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
package main
func filterInPlace(numbers []int, keep func(int) bool) []int {
n := 0
for _, val := range numbers {
if keep(val) {
numbers[n] = val
n++
}
}
return numbers[:n]
}
Breakdown
1
n := 0
Initializes a write pointer n to track the count and position of elements matching the filter criteria.
2
numbers[n] = val
Overwrites the element at the current write pointer n with the valid matching value.
3
n++
Increments the write pointer to prepare for the next matching element.
4
return numbers[:n]
Returns a slice header pointing to the same backing array but truncated to only contain the matching elements.