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.go32 chars2 lines
To remove item number 3
(value 3
at index 2
), we can use slicing as follows:
main.go67 chars3 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.go34 chars2 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.
gistlibby LogSnag