Home > Article > Backend Development > How to copy golang slice
#Golang's slice is a pointer structure pointing to the underlying array.
This structure has three attributes, 1. Pointer to the array, 2.len: the number of elements in the slice 3.cap: the amount of memory occupied by the slice.
Only by deeply understanding these three attributes can you avoid making mistakes when using slice. (Recommended learning: go)
Correctly understand variables and sharing
Multiple slices can share underlying data and reference arrays Some intervals may overlap
The above is a sentence from the golang Bible. A deep understanding of this sentence is very meaningful for schedule programming.
When shared data will be modified by other variables
func f1() { a1 := []int{1,2,3,4,5,6} a2 := a1 a3 := a1[1:3] a1[1] = 999 fmt.Println("a1=",a1,"a2=",a2,"a3=",a3) }
Running results
a1= [1 999 3 4 5 6] a2= [1 999 3 4 5 6] a3= [999 3] Process finished with exit code 0
We clearly see the data sharing , a1 is modified at this time, both variables are modified
When will it not be modified
func f2() { a1 := []int{1,2,3,4,5,6} a2 := a1 a3 := a1[1:3] a2 = append(a2,888) a1[1] = 999 fmt.Println("a1=",a1,"a2=",a2,"a3=",a3) }
Running result
a1= [1 999 3 4 5 6] a2= [1 2 3 4 5 6 888] a3= [999 3] Process finished with exit code 0
Although a1 is modified, a2 is not modified. We know that the append function will face memory reallocation. So when a2 appends, it will re-apply for memory space, copy the original array and add the new value. That is, when the append operation occurs, a2 no longer shares memory with a1.
When copying a slice, if you face multiple variables pointing to an array at the same time, you must consider data sharing and memory reallocation.
The above is the detailed content of How to copy golang slice. For more information, please follow other related articles on the PHP Chinese website!