Array
An array is a value type: The array length must be specified []int is a slice [5]int is an array
Note: The size of the array is part of the type. therefore [5]int and [25]int are different types. Therefore, the array cannot be resized. slicing resolves this issue
A: = [3]int{5, 78, 8}
var b [5]INTB = a//not possible since [3]int and [5]int is distinct types
When an array is assigned to a new variable, a copy of the original array is assigned to the new variable. If a change is made to a new variable, it is not reflected in the original array. Value passing and parameter passing (reference) value passing: Copy reference passing: No
The go language does not generally use arrays directly
Statement
var array1 [5]intarray2: = [3]int{1,2,3}array3: = [...] Int{1,2,3}var grid [4][5] bool
Length
You can get the length of the array by passing the array as an argument to the Len function.
Traversing arrays: Traditional
A: = [...] float64{67.789.8} for0/ / Looping from 0to the length of the array FMT. Printf ("%d th element of a is%.2f\n", I, A[i]) }
Iterating through an array: Range
For _,v: = Range Arr3 { fmt. Println (v) }for i,v: = Range Arr3 { fmt. Println (i,v) }for I: = Range Arr3 { fmt. Println (Arr3[i]) }
Note: You can omit variables by _ Anywhere
Multidimensional arrays
var Threedim [5] [4]int
Slice
Slices do not need to be set in length compared to arrays, and are relatively free in [].
Concept:
Conceptually, slice is like a struct, which contains three elements: a pointer to the length of the slice specified starting position in the array, that is, the length of the slice, which is the length of the slice starting position to the last position of the array.
The slice itself has no data, and any changes to the slice of a view on the underlying array will be reflected in the underlying array.
A slice defaults to nil before being initialized, with a length of 0
Grammar
Defined:
Arr: = [...] int{0,1,2,3,4,5,6}
S: = arr[2,6]
UPDATESLICE:S1: =arr[2:] S2: = arr[:]
Reslice:s: = Arr[2:6] s = s[:3] s = s[1:] s = arr[:]
add element: s = Append (s,val) If the cap is exceeded, the system will reassign the larger underlying array
Due to a value-passing relationship, the Append return value must be received if Len is large, the CAP starts at 32, after 64, and then 128
Append ()
Append appends one or more elements to the slice and returns a slice of the same type as slice
The Append function alters the contents of the array referenced by slice, affecting other slice that refer to the same array. However, when there is no space left in the slice (i.e. (cap-len) = = 0), the new array space is dynamically allocated.
The returned slice array pointer will point to this space, and the contents of the original array will remain unchanged; other slice referencing this array are unaffected
Copy ()
The copy function copy copies elements from the src of the source slice to the target DST, and returns the number of copied elements
Go 3 arrays, slices, functions