This is a creation in Article, where the information may have evolved or changed.
There are two ways to create a slice
Test: = []int{2,3}
Or use make, and we usually create more cases using made
For example:
Test: = Make ([]int, 5, 5)//Create a slice of type int, length 5, 5 capacity
Fmt. Println (len (test), Cap (test))//5 5
Test1: = Make ([]int, 3)//If no capacity is specified, the default capacity equals the initial length
Fmt. Println (Len (test1), Cap (test1))//3 3
The length and capacity of slice can be dynamically changed, slice is actually a part of the array
Test: = Make ([]int,0)//Create an array with a length of 0 and a capacity of 0
Fmt. Println (len (test), Cap (test))//0 0
Test = append (test, 1)
Fmt. Println (len (test), Cap (test))//1 1
Test = append (test, 1)
Fmt. Println (len (test), Cap (test))//2 2
Test = append (test, 1)
Fmt. Println (len (test), Cap (test))//3 4
When the capacity of the array is not enough, it will re-request a slice twice the current length, so in the process of use, especially frequent to a slice to append data, need to give as much as possible to a relatively accurate capacity, reduce the loss of the distribution process.
RELATED links:
Copy and append of slices