In this example, we will show you how to remove elements from a slice in Go with an example.
There is no built-in function to remove items from a slice. We can do the deletion with the append() function.
Go - slice remove element example
In the example, we delete an element and then two elements from the slice.
package main
import (
"fmt"
)
func main() {
days := []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
fmt.Println(days)
days = append(days[1:2], days[2:]...)
fmt.Println(days)
days = append(days[:2], days[4:]...)
fmt.Println(days)
}
Output:
[Monday Tuesday Wednesday Thursday Friday Saturday Sunday] [Tuesday Wednesday Thursday Friday Saturday Sunday] [Tuesday Wednesday Saturday Sunday]
Comments
Post a Comment