Remove an element from a slice in Go

Since Go slices don’t have a remove method or anything similar you need to do it yourself. Stack Overflow has a great thread on the best ways to achieve this, summarized here:

Order matters

If you need to retain the order, use this logic:

func remove(slice []int, s int) []int {
	return append(slice[:s], slice[s+1:]...)
}

This is inefficient because you may end up moving all elements, so only do this if you need to keep the order.

Order is not important

If you don’t care about the order it is much faster to swap the last element with the one to delete and return a slice without the last element.

func remove(s []int, i int) []int {
	s[i] = s[len(s)-1]
	return s[:len(s)-1]
}
Edit this page on GitHub