There are two concepts in slices: one is the len length, and the other is the cap capacity. The length refers to the maximum subscript 1 that has been assigned a value. It can be used through the built-in function len() get. Capacity refers to the maximum number of elements that the slice can currently hold, which can be obtained through the built-in function cap().
Slices can be initialized through arrays or through the built-in function make(). When initializing, len=cap. When appending elements, if the capacity cap is insufficient, the capacity will be expanded by 2 times of len.
s :=[] int {1,2,3 }
Directly initialize the slice, [] indicates the slice type, {1,2,3} initialization value is 1,2,3 in order. Its cap=len=3
s := arr[:]
Initialize the slice s, is a reference to the array arr
s := arr[startIndex:endIndex]
Create the elements in arr from subscript startIndex to endIndex-1 as a new slice
For more golang knowledge, please pay attention to PHP Chinese websitegolang tutorial column.
The above is the detailed content of How to assign length to slice in golang. For more information, please follow other related articles on the PHP Chinese website!