go / intermediate
Snippet
Preventing memory leaks when slicing arrays using copy
Slicing a slice (e.g., numbers[:2]) keeps the reference to the entire underlying array in memory, preventing GC reclamation. Using the built-in copy function copies only the needed subset of elements into a smaller new slice, freeing the large underlying memory block.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package mainimport "fmt"func getFirstTwo(numbers []int) []int {res := make([]int, 2)copy(res, numbers[:2])return res}func main() {largeSlice := make([]int, 1000000)largeSlice[0] = 42largeSlice[1] = 99smallSlice := getFirstTwo(largeSlice)fmt.Println(smallSlice)}
Breakdown
1
res := make([]int, 2)
Creates a brand new slice of the exact size needed to store the subset.
2
copy(res, numbers[:2])
Copies the elements from the source slice to the destination slice, decoupling them from the large underlying array.
3
return res
Returns the new small slice, allowing the large source slice to be garbage collected.