Skip to content

Efficiently Keep Order When Removing Elements From a Slice in Golang

If you are interested in the order of your slice and want to remove some of them in an efficient way this snippet is for you.

Check this working example:

package main

import "fmt"

func main() {

	userList := []string{"a", "b", "c", "d"}

	userList = removeKeepOrder(userList, 1)

	fmt.Println(userList)
}

func removeKeepOrder(s []string, i int) []string {
	// check the index
	if i >= len(s) || i < 0 {
		return s
	}

	// copy elements after i to i position
	copy(s[i:], s[i+1:])

	// remove the last item
	return s[:len(s)-1]
}

If the order is not important for you check this snippet: Golang: Efficiently Remove an Element From a Slice (No Order)

Leave a Reply

Your email address will not be published. Required fields are marked *