All of the following content can be viewed on Site B. If you like watching videos, you can check out this chapter or a series of video tutorials on site B.
www.bilibili.com/video/BV1Yf…
Go language Slice
The length of Go arrays cannot be changed, and such collections are not suitable for certain scenarios. Go provides a flexible and powerful built-in type slice (” dynamic array “). Compared with arrays, the length of slices is not fixed, and you can append elements, which may increase the size of slices.
A slice is based on an array. You have to have an array to have a slice. Its internal structure contains address, length, and capacity. Slicing is generally used to quickly manipulate a collection of data. Slices are of the reference type.
Value type and reference type
When we create an array. A memory address is generated in the content space. When we assign from one array to another, we create a new memory space in memory space. But our slice is the same as an array of spatial memory data collection blocks.
define
Var Variable name [] typeCopy the code
Note and var variable names […] Type distinction, added… We’re defining our array.
Length and capacity of slice
What’s the length? It’s kind of like an array, how many elements do we have? That’s our length. So the capacity is the maximum length that our slice can withstand.
Take, for example, our cups. How much water can it hold is its capacity. How much water is filled is its length.
For example, in the figure above, if we have an array {0,1,2,3,4,5,6,7}, we start at 0 and remove five elements. So this slice has {0,1,2,3,4}, which is our length. Because we get it from 0 then the size of this slice is going to be the length of our array and we cut out our 0, which is 8 minus 0.
In order to use slices in the development process, we must build on the array. Is there any way to create our slices without array? The answer is yes it is ours or use the make() function to create slices:
var slice1 []type = make([]type.len) can also be abbreviated slice1 :=make([]type.len)
make([]T, length, capacity)
Copy the code
Append () and copy()
These are the two functions that GO gives me to slice.
There’s a demonstration in the video, but I’m not going to talk about it here one of them is append. One is to copy a new slice, and the direction of the memory address will change.