Getting Started with Golang: Talk about the append function in detail

In the last section, we talked about the use of the append function in the go language. Students who have doubts can go to the homepage to look it up. We won’t go into details here.

Let's take a deeper look at the append function in go.

① First, let's define a slice iArray1 and print its value to see.

We can see that it is just two lines of code, defining variables and printing output. Hahaha

② Then, let's define slice iArray2, and the memory points to slice iArray1, then we remove elements from slice iArray2, and then print out both slices.

 

 From the figure, we can see that the element "2" in the two slices has been removed. In the slice iArray2, it is true that the element has been removed, but we look carefully at the slice iArray1 and find that although one element has been removed, the total number of elements has not decreased. Why is this? In fact, removing elements through append in the go language is actually reconnecting the front and back parts. In essence, it is to move the elements after the deletion point forward and reconnect the memory.

 Let's analyze it carefully:

Take a closer look at the figure below, in fact, at the very beginning, slices iArray1 and iArray2 point to the same memory address.

 Then we used the append function to manipulate the value on this memory address, and we found that the value is different, so let's print the memory address at this time to see.

 Seeing this, I'm sure many people are the same as me at the beginning. What's going on? It points to the same memory address, but why the printed values ​​are different? At this point, let's try printing the lengths of the two slices again.

It turns out that after the append is executed, the elements in the entire memory address are actually operated. However, the length of the slice iArray2 is only 6, so only the first six elements can be seen, and it does not re-allocate a piece of memory.

Next, draw an ugly picture to summarize:

(1) At the beginning, the initial lengths of slices irray1 and iarray2 are both 7, and both point to the memory address 0xc00000a240.

(2) append operates on the value on the memory 0xc00000a240: after append kills the element "2", the following elements move forward, so the position of the element "2, 3, 4, 5" is replaced by "3, 4, 5, 6", but the position of the element "6" has no element to replace it, and the original value is retained. So after the append operation, the value stored in the memory 0xc00000a240 becomes "0,1,3,4,5,6,6".

(3) After append is executed, slices irray1 and iarray2 still point to the memory address 0xc00000a240.

(4) Since the return value of append is assigned to slice iarray2, the length of slice iarray2 becomes 6. So the printout is [0 1 3 4 5 6], but the length of irray1 is still the original 7, so the printout is [0 1 3 4 5 6 6].

Guess you like

Origin blog.csdn.net/weixin_45963929/article/details/125874039