Three new books, Go Optimizations 101, Go Details & Tips 101 and Go Generics 101 are published now. It is most cost-effective to buy all of them through this book bundle in the Leanpub book store.

How to efficiently delete contiguous elements of a slice while keeping the element order?

Assume:
  1. the involved slice is s and its type is []E, where E is the slice element type.
  2. we want to delete the elements in the subslice s[from:to] and from <= to.

Way 1: use the build-in copy function

	s = s[:from + copy(s[from:], s[to:])]

Way 2: use the build-in append function

	s = append(s[from:], s[to:]...)

Way 3: use the slices.Delete function (Since Go 1.21)

import "slices"

	s = slices.Delete(s, from, to)

Some notes

Note 1

There is a detail we should be aware of:

So the first way is preferred over the second way.

Note that, in Go 1.21, the implementation of the slices.Delete function was the same as the way 2. So it was also inefficient when from == to. Since Go 1.22, the problem has been removed.

(The detail is collected in the Go Optimizations 101 book.)

Note 2

If it is important to try to shorten the lifespan of other values referenced by the freed-up elements (which contain pointers), then we need do more (for both way 1 and way 2) by clearing the freed-up elements with either of the following two manners:

Manner 1 (since Go 1.21):

	// The "clear" built-in function was introduced in Go 1.21.
	clear(s[len(s):len(s)+to-from])

Manner 2 (assume the zero literal of E is zeroE):

	{
		temp := s[len(s):len(s)+to-from]
		for i := range temp {
			temp[i] = zeroE
		}
	}

If Go toolchain 1.21 is used, then we should also clear the freed-up elements by ourselves after calling the slices.Delete function (with either of the above two manners). Since Go 1.22, the slices.Delete function will automatically clear the freed-up elements.


Index↡

The Go 101 project is hosted on Github. Welcome to improve Go 101 articles by submitting corrections for all kinds of mistakes, such as typos, grammar errors, wording inaccuracies, description flaws, code bugs and broken links.

If you would like to learn some Go details and facts every serveral days, please follow Go 101's official Twitter account @zigo_101.

Tapir, the author of Go 101, has been on writing the Go 101 series books and maintaining the go101.org website since 2016 July. New contents will be continually added to the book and the website from time to time. Tapir is also an indie game developer. You can also support Go 101 by playing Tapir's games (made for both Android and iPhone/iPad):
Individual donations via PayPal are also welcome.

Index: