Go: Clear a slice

To remove all elements, set the slice to nil:

a := []string{"A", "B", "C", "D", "E"}
a = nil
fmt.Println(a, len(a), cap(a)) // [] 0 0

This will release the underlying array to the garbage collector (assuming there are no other references).

Note that nil slices and empty slices are very similar:

Keep allocated memory

To keep the underlying array, slice the slice to zero length:

a := []string{"A", "B", "C", "D", "E"}
a = a[:0]
fmt.Println(a, len(a), cap(a)) // [] 0 5

If the slice is extended again, the original data reappears:

fmt.Println(a[:2]) // [A B]

Comments

Be the first to comment!