remove an item from a slice in go

To remove an item from a slice in Go, there are different approaches, but one of the most common is to use slicing again to create a new slice with the remaining items.

Suppose we have the following slice of integers:

main.go
numbers := []int{1, 2, 3, 4, 5}
32 chars
2 lines

To remove item number 3 (value 3 at index 2), we can use slicing as follows:

main.go
index := 2
numbers = append(numbers[:index], numbers[index+1:]...)
67 chars
3 lines

This creates a new slice by appending the items before the index (excluding it) with the items after the index (again, excluding it).

Now the updated numbers slice has the item removed:

main.go
fmt.Println(numbers) // [1 2 4 5]
34 chars
2 lines

Note that the original slice is modified by this operation. If you need to keep the original slice, you can create a copy of it before removing the item.

related categories

gistlibby LogSnag