What happens to "wasted" space in slices?

The garbage collector can’t collect that unused space. Any pointer to an allocation will keep that whole allocation alive. At least, that’s true with the current collector; maybe someday we’ll make it better.

This is particularly relevant in cases like this:

t1 := new(T)
t2 := new(T)
s := []*T{t1, t2}
s = s[1:]

Even though t1 is no longer accessible, the garbage collector still considers it live, because s points to an allocation (a [2]*T), and that allocation points to t1. If t1 points to yet other things, it may keep an arbitrary amount of storage live. So when T has pointers in it, it may make sense to do this instead:

t1 := new(T)
t2 := new(T)
s := []*T{t1, t2}
s[0] = nil
s = s[1:]

To make sure the backing store of s no longer points to t1.

2 Likes