I'm getting some unexpected behavior when I try to loop through a slice and remove every element in sequence to print the remaining elements, using the suggested Delete method from SliceTricks. For example, when I try and loop through a slice that contains the letters [A B C]
, I expect the output to be [B C]
, [A C]
, [A B]
in that order:
Method 1
package main
import "fmt"
func main() {
a := []string {"A", "B", "C"}
for i, _ := range a {
fmt.Println(append(a[:i], a[i+1:]...))
}
}
However, the output here is surprising to me. It outputs [B C]
three times.
I did eventually get my expected behavior by doing the following:
Method 2
package main
import "fmt"
func main() {
a := []string {"A", "B", "C"}
for i, _ := range a {
result := make([]string, 0)
result = append(result, a[:i]...)
result = append(result, a[i+1:]...)
fmt.Println(result)
}
}
What is causing the unexpected behavior in method 1 and is there a better way to achieve this other than method 2?