Unexpected Changes in a Range Loop

Hello, everyone:

I met a problem when writing a code for a problem on LeetCode (not important). I wrote a function but it did not work as I expected. I moved my code into the playground.

Here is my problem:

I print every loop and the output around the line item [1 1 2] makes me confused.

Before appending, the value of the variable result is [[] [1] [1 1] [2] [1 2] [1 1 2] [2 2] [1 2 2] [1 1 2 2]] which is same as my expect.

But after appending variable n, which is 3, into an element without assignment, the value changed into [[] [1] [1 1] [2] [1 2] [1 1 2] [2 2] [1 2 2] [1 1 2 3]].

I don’t know why it happened and what can I do to resolve it?

Slices are not immutable. When you start off with a slice like []int{}, it has a capacity of zero. The first append allocates a new slice with capacity 1 and stores the appended value into that slice. The 2nd append creates a new slice with double the capacity from 1 to 2 and stores the appended value in. The third time you append into the alice, you allocate yet another slice with doubled capacity: 4. The 4th time your slice from the 3rd append still has available capacity so that slice is reused without allocating a new one.

1 Like

Well, I got it.

The first few loops bypass this issue because a new slice is allocated. I understand now!

Thanks a lot! You save my life!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.