英文:
Why does slices.Delete() in golang copy the next element?
问题
示例代码:
func main() {
bar := []string{"Monday", "Tuesday", "Wednesday"}
bar = append(bar[:0], bar[1:]...) // 我想删除 'Monday'
fmt.Println(bar) // 输出 [Tuesday Wednesday]
}
我不明白为什么会得到一个复制的 'Wednesday'。我原本期望得到一个只有两个元素的切片。
英文:
Sample code:
func main() {
bar := []string{"Monday", "Tuesday", "Wednesday"}
slices.Delete(bar, 0, 1) // I want to delete 'Monday'
fmt.Println(bar) // prints [Tuesday Wednesday Wednesday]
}
I don't understand why I get a copy of 'Wednesday'. I was expecting a two-element slice.
答案1
得分: 4
slices.Delete
返回修改后的切片。你应该这样使用它:
bar = slices.Delete(bar, 0, 1)
这是因为删除操作会将切片中的元素向前移动,然后返回一个较短的切片,但原始切片 bar
保持不变。
英文:
slices.Delete
returns the modified slice. You should use it as:
bar=slices.Delete(bar, 0, 1)
This is because the delete operation shifts the elements in the slice, and then returns a shorter slice, but the original slice bar
remains the same.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论