This is a creation in Article, where the information may have evolved or changed.
Slice is a very important topic in go. We don't use slices to describe them, because the slices here refer specifically to the slices of the array.
Let's define slice first:
Slice expressions construct a substring or Slice from a string, array, pointer to array, or Slice. There is variants:a simple form that specifies a low and high bound, and a full form that also specifies a bound on The capacity.
Constructs a substring from a string or constructs a slice from an array, and assigns the substring or pointer to the slice to the slice. In other words, slice is a pointer to a string or an array.
On the surface, slice is something very similar to an array, but the biggest difference between the two is that the array is fixed and slice can change its length.
Basic syntax for slice:
1
a[low : high]
Create an array
A: = [5]int{1, 2, 3, 4, 5}
Create slices
S: = A[1:4]
The type of element in slice S is int,length (length) is 3 (high-low), capacity (capacity) is 4
Ellipsis for 2 slices
For convenience (original), any of the indices is omitted. A missing low index defaults to zero; A missing high index defaults to the length of the sliced operand. (for convenience, any index can be ignored, the starting index defaults to 0, and the end index defaults to the length of slice)
a[2:] // same as a[2 : len(a)]a[:3] // same as a[0 : 3]a[:] // same as a[0 : len(a)]
3
slicer := make([]int, 10)
You can create a new slice by make, the first parameter is the element type in slice, and the second parameter is the capacity of this slice.
The realization principle of slice
When we create a slice, the following things happen:
Creates an array of parameter 2 lengths that match the element type of parameter 1.
Creates a pointer to this array and assigns it to the slice.
The pointer here is actually the address that points to the location of the array element that corresponds to the slice index value start value.
func main() { a := [5]int{1, 2, 3, 4, 5} var d *[5]int = &a println(d) println(a[0:4]) println(a[1:4])}
Results:
0x220822bf08//原始数组地址[4/5]0x220822bf08//对应切片a[0:4]地址[3/4]0x220822bf10//对应切片a[1:4]地址