英文:
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
我打印了所有迭代的切片的len
和cap
,但它们似乎按预期每次迭代都减少了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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论