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.