This is a creation in Article, where the information may have evolved or changed.
Conclusion: It is important to use append operation carefully in Golang slice. When the cap does not change, slice is a reference to the array, and append modifies the value of the referenced arrays. After the append operation causes the CAP to change, the referenced array is copied and then the reference relationship is severed.
The code and comments are as follows:
Package Main
Import (
"FMT"
)
Func Main () {
Array: = []int{10, 11, 12, 13, 14}
Slice: = Array[0:4]//Slice is a reference to the array
Fmt. Println ("array:", array)//array: [20 21 12 13 14]
Fmt. Println ("slice:cap=", Cap (Slice), ", value=", slice)//slice:cap= 5, value= [10 11 12 13]
Array[0] + = 10//will be modified at the same time slice[0]
SLICE[1] + = 10//will be modified at the same time array[1]
Fmt. Println ("\nafter add 10")
Fmt. Println ("array:", array)//array: [20 21 12 13 14]
Fmt. Println ("Slice:", slice)//slice: [20 21 12 13]
Slice1: = Append (slice, 15)//Add new element, cap is still 5,array[4] into 15
Fmt. Println ("\nafter append 15")
Fmt. Println ("array:", array)//array: [20 21 12 13 15]
Fmt. Println ("Slice:", slice)//slice: [20 21 12 13]
Fmt. Println ("slice1:cap=", Cap (Slice1), ", value=", Slice1)//slice1:cap= 5, value= [20 21 12 13 15]
ARRAY[2] + = 20//will also modify slice[2], slice1[2]
SLICE[3] + = 20//will also modify ARRAY[3], slice1[3]
SLICE1[4] + = 20//will be modified at the same time Array[4]
Fmt. Println ("\nafter add 20")
Fmt. Println ("array:", array)//array: [20 21 32 33 35]
Fmt. Println ("Slice:", slice)//slice: [20 21 32 33]
Fmt. Println ("Slice1:", Slice1)//Slice1: [20 21 32 33 35]
Slice2: = Append (Slice1, 16)//Add new element 16,cap changed to 10,array value unchanged
Fmt. Println ("\nafter append 16")
Fmt. Println ("array:", array)//array: [20 21 32 33 35]
Fmt. Println ("Slice:", slice)//slice: [20 21 32 33]
Fmt. Println ("Slice1:", Slice1)//Slice1: [20 21 32 33 35]
Fmt. Println ("slice2:cap=", Cap (Slice2), ", value=", slice2)//slice2:cap=, value= [20 21 32 33 35 16]
Array[0] + = 30/modify Array[0] value, slice[0], slice1[0] values will change, but the value of slice2[0] does not change
SLICE[1] + = 30/modify Slice[1] value, array[1], slice1[1] values will change, but the value of slice2[1] does not change
SLICE1[2] + = 30/modify Slice1[2] value, array[2], slice[2] values will change, but the value of slice2[2] does not change
SLICE2[3] + 30//modify SLICE2, array, slice, Slice1 value unchanged
Fmt. Println ("\nafter add 30")
Fmt. Println ("array:", array)//array: [50 51 62 33 35]
Fmt. Println ("Slice:", slice)//slice: [50 51 62 33]
Fmt. Println ("Slice1:", Slice1)//Slice1: [50 51 62 33 35]
Fmt. Println ("Slice2:", Slice2)//SLICE2: [20 21 32 63 35 16]
}