How to Remove From a Slice in Golang

Hey! If you love Go and building Go apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

Want to learn how to build better Go applications faster and easier? You can.

Check out my course on the Go Standard Library. You can check it out now for free.


To remove an element from a slice in Go, you can use the append() function to create a new slice that does not include the element you want to remove. Here is an example of how to do this:

package main

import "fmt"

func main() {
	// Create a slice of integers
	s := []int{1, 2, 3, 4, 5}

	// Remove the element at index 2 (which is 3)
	s = append(s[:2], s[3:]...)

	// Print the resulting slice
	fmt.Println(s) // Output: [1 2 4 5]
}

In this example, we create a slice s containing the elements 1, 2, 3, 4, and 5. We then use the append() function to create a new slice that includes all of the elements of s except for the element at index 2 (which is 3). The resulting slice is then printed to the console.

Note: This method of removing an element from a slice is efficient because it does not require allocating a new slice or copying the elements of the original slice. However, it does modify the original slice, so be aware of this if you are working with slices that you do not want to modify.


Questions or comments? Reach out to me


Learn how to leverage the Go Standard Library like a PRO.

I just created a new course, The Go Standard Library, check it out!