Go language Learning Note 11: slicing (slice)
The concept of slicing I learned from the Python language when I felt that it was really useful. It's not as tedious to write as the Java language. But I think the future Java syntax will also support.
Defining slices
Slices can be defined using the Make function, or you can create a slice of an unspecified size like a variable declaration.
var x []int = make([]int, 3);y := make([]int, 3);z := []int {1, 2, 3};
Make has three parameters, the first of which is the type (array type, so with square brackets), the second is the length Len, and the third is the capacity cap. The length is good to understand, is the value of how much. And the capacity is not good understanding, capacity is designed to reduce the number of automatic expansion, in order to reduce the number of expansion, you can come up on a larger set.
Slicing operations
s := arr[:]s := arr[1:2]s := arr[1:]s := arr[:2]
Len () and Cap () functions
This two function in order to get the slices of Len and cap.
Empty (nil) slices
A slice defaults to nil before being initialized, with a length of 0.
Append () and copy () functions
Append is to add elements to the original slice. Copy is a duplicate of the original slice, if not copied, then modify the new slice content, the original corresponding elements will also be modified.
var x []intx = append(x, 1);x = append(x, 2, 3, 4);y := make([]int, len(x), cap(x) * 2)copy(y, x);
Go language Learning Note 11: slicing (slice)