To remove elements from a slice in Golang, you can use the append
function along with slicing.
Here is an example that demonstrates how to remove elements from a slice:
package main
import "fmt"
func main() {
// Creating a slice
numbers := []int{1, 2, 3, 4, 5}
// Removing an element at index 2
index := 2
numbers = append(numbers[:index], numbers[index+1:]...)
fmt.Println(numbers) // [1 2 4 5]
}
In this example, we define a slice numbers
with elements [1, 2, 3, 4, 5]
. We want to remove the element at index 2 (value 3).
To remove the element at index 2, we use the append
function to concatenate the slice from index 0 to index 1 with the slice from index 3 to the end of the slice. This effectively removes the element at index 2 from the original slice.
After removing the element, the numbers
slice becomes [1, 2, 4, 5]
.