0

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

Floating Sunfish
  • 4,920
  • 5
  • 29
  • 48

1 Answers1

-1

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

Floating Sunfish
  • 4,920
  • 5
  • 29
  • 48