Free memory of slice

My code would never access the elements of original slice s from 0 to 89. In this situation, could Go garbage collector free the memory allocated to them(s[0:89])?

It could, but it currently does not.

Or the memory would not be freed since it seems they still share the same underlying array on which slice s is built?

Yes, the memory will not be free’d. This is similar to other languages that support “subslicing” vector types, like Java’s String type.

If not, how should I do if I want to free those memory?(For example, I have to make a deep copy of slice and never access s)

x := make([]int, 10)
copy(x, s)
s = nil // or let all references to s go out of scope
1 Like