The difference between array and slice in golang

The difference between array and slice in golang

Array: array1 := [3]int{1,2,3}
slice: array2 := []int{1,2,3} This only append
slice can be directly append res := append(array2,10)

But if the slice wants to assign
array2[3] = 20 like this, it will report an error because no memory space is allocated, so make is required at this time

array3 := make([]int,10)
array3[3] = 20 So the old value can be assigned.
Note that
array3 := make([]int,10)
array3[11] = 20 Is this okay? An error will be reported. This is because the defined length is 10, so an error will be reported when the 11th position is given. What should I do
at this time? At this time, append is needed, and append will automatically expand.

To judge whether the arrays are equal, use
if shu1 == shus2.
Slice needs to use reflect.DeepEqual(slice1, slice2)

Summary: 1. Only slices can append
2. Arrays can be assigned directly, but they must be assigned within the specified length, and an error will be reported if they exceed the range.
3. Slices can be appended directly, but the assignment needs to be done after make. After the slice has a specified size, assign Can not exceed the range, use append

Insert picture description here
Insert picture description here

Note: Array is value copy, slice and map are passed by reference, if you want to make a copy again, use copy

Summary: An array is a value copy. A slice refers to an address that points to the same array, but if you use the copy function, it is equivalent to copying the slice again, instead of pointing to an array
Insert picture description here
a := make(map[int]string ,8) The second parameter represents the capacity, the second element of the previous slice is the length, and the third parameter is the capacity
map It is not possible to directly use cap to obtain capacity

Guess you like