Go: Delete an element from a slice

Here's how to remove the element at index i from a slice.

Fast version (changes order of elements):

a := []string{"A", "B", "C", "D", "E"}
i := 2

a[i] = a[len(a)-1] // Copy last element to index i
a[len(a)-1] = ""   // Erase last element (write zero value)
a = a[:len(a)-1]   // Truncate slice

fmt.Println(a) // [A B E D]

This is fast: the code copies a single element and runs in constant time.

Slow version (maintains order of elements):

a := []string{"A", "B", "C", "D", "E"}
i := 2

copy(a[i:], a[i+1:]) // Shift a[i+1:] left one index
a[len(a)-1] = ""     // Erase last element (write zero value)
a = a[:len(a)-1]     // Truncate slice

fmt.Println(a) // [A B D E]

This could be slow: the code copies len(a) − i − 1 elements and runs in linear time.

Comments

Be the first to comment!