Use append to pursue elements after slice, such as
nums:=[]int{1,2,3}result:=append(nums,4)fmt.Println(result)
This code is simple, and the value of the output result is: [1 2 3 4]
The problem is that when you do this, the value of the array on which the original slice (i.e. nums) is based will not change. In Golang, if more than one slice is based on the same array, the data for these slice is shared (not one copy per slice). It also says that if you change the contents of an array, the value of all slice based on it will change, but not all of the time, the value of nums in this code does not change.
To answer this question, you first need to understand the Append function implementation principle:
1. If the nums cap is sufficient, the element is appended directly to the array that the nums points to, and the returned slice and the original slice are the same object. Obviously, the value of the original slice will change in this case!
2. If the nums cap is not sufficient (this is the case), an array space is reassigned to store the data, and the slice that points to the new array is returned. At this time the original slice pointed to the array did not change anything!
3. Of course, in any case, the result of the return is appended to the slice, which is no problem!
The following code is used to verify the problem:
(1) The value in the function test1 nums changes, because the Len of Nums[:2] is 2,cap 3, so the cap is still sufficient to append an element;
(2) The value in the function test2 nums does not change, because the cap for Nums[:2] is not sufficient, so an array is reassigned to store the new data, and nums the old array is still stored.
Func test1 () {nums: = []int{1,2,3} _ = Append (nums[:2],4) FMT. Println ("Test1:", nums)//nums changes because the cap is big enought, the original array is modified.} Func test2 () {nums: = []int{1,2,3} c: = Append (nums[:2], []int{4,5,6}...) FMT. Println ("Test2:", Nums) fmt. Println ("cc:", c)//nums dont' t change because the cap isn 'T big enought. A new array is allocated whileThe nums still points to the old array. Of course, thereturnValue of append points to the new array.}
< end >
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The problem of changing the original array when the Append of Golang:slice