我得到了可接受的答案解决方案的索引超出范围错误。原因:范围开始时,不是一个一个地迭代值,而是一个索引迭代。如果您在范围内修改切片,则会引起一些问题。
旧答案:
chars := []string{"a", "a", "b"}
for i, v := range chars {
fmt.Printf("%+v, %d, %s\n", chars, i, v)
if v == "a" {
chars = append(chars[:i], chars[i+1:]...)
}
}
fmt.Printf("%+v", chars)
预期:
[a a b], 0, a
[a b], 0, a
[b], 0, b
Result: [b]
实际:
// Autual
[a a b], 0, a
[a b], 1, b
[a b], 2, b
Result: [a b]
正确方法(解决方案):
chars := []string{"a", "a", "b"}
for i := 0; i < len(chars); i++ {
if chars[i] == "a" {
chars = append(chars[:i], chars[i+1:]...)
i-- // form the remove item index to start iterate next item
}
}
fmt.Printf("%+v", chars)
资料来源:https : //dinolai.com/notes/golang/golang-delete-slice-item-in-range-problem.html