This is a creation in Article, where the information may have evolved or changed.
Array type
is a fixed-length array that must be determined before using the array length
array
golangarrayFeatures:
golangThe array in is 值类型 , that is, if you assign an array to another array, then the entire array is actually copied a copy of the
- If
golang the array in the function is an argument, the actual passed argument is a copy of the array, not the pointer to the array
arrayis also part of the length, which means it Type [10]int [20]int is not the same.
sliceType
sliceis a reference type and is a dynamic pointer to an array slice.
sliceis a variable-length data structure that always points to the underlying array array .
1. Create Slice
动态数组创建,类似创建数组,但是没有指定固定长度var al []int //创建slicesl := make([]int,10) //创建有10个元素的slicesl:=[]int{1,2,3} //创建有初始化元素的slice
2. Create the array first, and set up the slice based on the array slice
var arr =[10]{1,2,3,4,5。6} sl := arr[2:5] //创建有3个元素的slice
3.slice has some easy-to-operate
- `slice`的默认开始位置是0,`ar[:n]`等价于`ar[0:n]` - `slice`的第二个序列默认是数组的长度,`ar[n:]`等价于`ar[n:len(ar)]`
The difference between an array and a slice
- When declaring an array, the length of the array is indicated in square brackets or ..., when the slice is declared, the square brackets are empty
- As a function parameter, the array passes a copy of the array, and slice passes the pointer.