Golang 重新切片问题

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

Golang Reslicing Issue

问题

我目前正在循环遍历一个切片,并每次删除第一个元素。

为了做到这一点,我使用以下代码:

mySlice = append(mySlice[1:])

前几次迭代都很顺利,但在后面的迭代中,一些元素被删除,一些元素被复制:

之前:

40.917
37.6384
41.2783
38.1481

之后:

40.917
37.6384
41.2783
37.6384
41.2783
38.1481

我打印了所有迭代的切片的lencap,但它们似乎按预期每次迭代都减少了1

更新:

我找到了问题所在:尽管我只是将我的切片传递给另一个函数以创建一个局部切片,但如果我操作局部切片,我的原始切片也会受到影响(噢!)。

Go Playground链接:https://play.golang.org/p/ca57tgusXD

英文:

I'm currently looping over a slice and removing the first element each time.

To do so, I am using the following code:

mySlice = append(mySlice[1:])

Everything goes fine for the first few iterations, but on later ones, some elements get removed and some get duplicated:

Before:

40.917
37.6384
41.2783
38.1481

After:

40.917
37.6384
41.2783
37.6384
41.2783
38.1481

I printed the len and cap of the slice for all iterations, but they seem to be decrementing by 1 for each iteration as expected.

UPDATE:

I figured out the problem: It seems that even though I am simply passing my slice to another function to create a local slice, if I manipulate the local slice, my original slice gets affected as well (D'oh!).

Go Playground Link: https://play.golang.org/p/ca57tgusXD

答案1

得分: -1

我终于弄清楚了!

我需要使用copy函数而不是使用:=来初始化我的本地切片。

Go Playground链接:https://play.golang.org/p/N9RzHOibdI

英文:

I finally figured it out!

I needed to use the copy function instead of initializing my local slices using :=.

Go Playground Link: https://play.golang.org/p/N9RzHOibdI

huangapple
  • 本文由 发表于 2017年7月1日 20:59:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/44861213.html
匿名

发表评论

匿名网友

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

确定