[Solved] creating new slice by appending to existing slice in golang


Here slice nums[:i] is created by slicing a bigger array nums. This leads to it having enough capacity to extend in place. So an operation like append(nums[:i], nums[i+1:]...) causes the elements in nums getting overridden by elements from nums[i+1:]. This mutates the original array and hence the behaviour.

As suggested by @icza the concept has been capture here.

To fix the Variant 2 we can use full slice expression like this

remaining := append(nums[0:i:i], nums[i+1:len(nums):len(nums)]...)

solved creating new slice by appending to existing slice in golang