go / intermediate
Snippet
Efficient Slice Filtering Without Allocating New Memory
Filtering a slice in Go can be done in-place by reusing the backing array of the input slice. This avoids allocating a new slice on the heap and improves memory performance.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package mainimport "fmt"func filterEven(numbers []int) []int {n := 0for _, x := range numbers {if x%2 == 0 {numbers[n] = xn++}}return numbers[:n]}func main() {nums := []int{1, 2, 3, 4, 5, 6}filtered := filterEven(nums)fmt.Println("Filtered:", filtered)fmt.Println("Original backing array modified:", nums)}
Breakdown
1
n := 0
Initializes an index tracker to write elements to the same underlying array.
2
numbers[n] = x
Overwrites the element at index `n` with the current matching element.
3
n++
Increments the index tracker to prepare for the next matching element.
4
return numbers[:n]
Returns a slice expression sharing the same backing array up to length `n`.