[Go - slice] Remove Elements from a slice in Go
Go has a special indexing syntax that forms the basis of removing one or more elements from a slice. I will teach you this syntax and show you its various forms.
Based upon that, I'll show you how to remove a single element from a slice. However, you may find this somewhat limiting. I also will show you a more typical example of removing elements from a slice as we iterate over it. This technique shows you how to remove multiple elements from a slice.
func main() {
all, err := loadChampions()
if err != nil {
log.Fatalf("An error occurred loading/parsing champions, err=%v", err)
}
// get 0 to 19
some := all[0:20]
// get 0 to 19
some = all[:20]
// get 10 to the end
some = all[10:]
// get all
some = all[:]
// Remove an element from the slice by index
// ... spread operator
// since append expects individual elements as its second and subsequent arguments,
// the ... operator is used to expand the second slice (all[11:]) into a series of arguments
// So the 10th element is removed
most := append(all[0:10], all[11:]...)
// Remove element with new slice
var filtered []champion
for _, champ := range all {
if !champ.hasClass("Sorcerer") {
filtered = append(filtered, champ)
}
}
// Remove elements by altering the slice in place
index := 0
for _, champ := range all {
if champ.hasClass("Sorcerer") {
continue
}
all[index] = champ
index++
}
all = all[:index]
}