What is a slice

As mentioned in the previous article, the length of an array is fixed, and the length of a slice is variable. Now let’s look at an example of slicing:

Func main () {slice1: string [] = {" a ", "b", "c"} / / [] is not defined in the length of the FMT. Println (slice1) / / / a b c slice2: = make (int [], 3, 5) // Use make to initialize an array slice of length 3 with the initial value of the element 0, Println(slice2) //[0 0 0] slice3 := make([]int, 3) // use make to initialize an array of length 3, Println(slice3) //[0 0 0 0 0]}Copy the code

Section capacity

There is an array in the underlying data structure of a slice. A slice can be seen as a reference to a fragment of an array, so an array is a variable of value type and a slice is a variable of reference type. The difference between value type and reference type: the variable of value type stores the actual data directly, while the variable of reference type stores the address of the data. The capacity of the slice is the length of the underlying array, so now the slice needs to be expanded, what if it exceeds the length of the underlying array?

Let’s take a look at how to expand slices, which must be very common:

slice4 := append(slice2, Println(slice4) //[0 0 0 3 4 5 6 7 8 9]Copy the code

What if we use arrays for expansion:

Array1: = [3] string (" 1 ", "2", "3") array2: = append (array1, "4", "5") / / an error,  first argument to append must be slice, fmt.Println(array2)Copy the code

The append method is used specifically for slicing. All elements of an array are defined and can only be modified. As mentioned in the previous article, the default values of the array element type are not given by default.

The original array is so useless that it feels like nothing can be done. When the capacity of the underlying array is exceeded, the underlying array will be automatically expanded, and the original elements and new elements will be copied to the new slice. This slice is based on the old array, and the underlying array will never change, just add elements after it. Array principle expansion belongs to an expansion knowledge, generally according to the capacity of the underlying array 1.25 times expansion, if the added elements are too many, this multiple is 2 times, interested in baidu search for the expansion principle.

conclusion

The capacity of an array is always its length, and the capacity of a slice is the length of the underlying array. The concept that slicing has one more capacity than array is often asked in interviews, but in practice, it is unnecessary to care about this problem in most cases. However, all the design details of Go language must be clear, otherwise its advantages will not be shown when it is actually used.