slices.Delete()函数在golang中为什么会复制下一个元素?

huangapple go评论83阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年1月5日 08:42:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75012785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定