Skip to content

Golang: Efficiently Remove an Element From a Slice (No Order)

You are writing a piece of code that it is important for you to have the best performance, if you are working with the slices in Golang removing items from it is not straightforward!

This method removes an item from the slice without keeping the order but it is super efficient:

package main

import "fmt"

func main() {

	slice := []string{"1", "2", "3", "4"}

	fmt.Println(remove(slice, 1))

func remove(s []string, index int) []string {
	// copy last item into the index we want to remove
	s[index] = s[len(s)-1]

	// return the slice except the last item
	return s[:len(s)-1]

Note: Just remember indexes start from 0.


1 thought on “Golang: Efficiently Remove an Element From a Slice (No Order)”

  1. Pingback: Efficiently Keep Order When Removing Elements From a Slice in Golang – Code Paste

Leave a Reply

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