I am iterating through a slice in golang and picking off elements one by one. The problem I am having is that after I remove an item I should either reset the index or start from the beginning but I'm not sure how.
package main
import (
"fmt"
)
func main() {
x := []int{1, 2, 3, 7, 16, 22, 17, 42}
fmt.Println("We will start out with", x)
for i, v := range x {
fmt.Println("The current value is", v)
x = append(x[:i], x[i+1:]...)
fmt.Println("And after it is removed, we get", x)
}
}
Will Return the following:
We will start out with [1 2 3 7 16 22 17 42]
The current value is 1
And after it is removed, we get [2 3 7 16 22 17 42]
The current value is 3
And after it is removed, we get [2 7 16 22 17 42]
The current value is 16
And after it is removed, we get [2 7 22 17 42]
The current value is 17
And after it is removed, we get [2 7 22 42]
The current value is 42
panic: runtime error: slice bounds out of range
goroutine 1 [running]:
main.main()
/tmp/sandbox337422483/main.go:13 +0x460
What is the idiomatic way to do this? I immediately thing i-- or i = i-1 coming from Python.