In go arrays, the length is part of the data type [3]int *[3]int
Notes and details on using arrays
1) An array is a combination of multiple data of the same type. Once an array is declared/defined, its length is fixed and cannot be changed dynamically.
var a [3]int
a[0] =1.1 这样是不行的,必须是整数
2) var arr [ ]int then arr is a slice ( if there is no size written in [], then this is a slice )
3) The elements in the array can be of any data type, including value types and reference types , but they cannot be mixed.
var b = [10]*int{&i, &j, &k}
fmt.Println(len(b))
fmt.Println(*b[0], *b[1], *b[2])
0xc0000a60f8 0xc0000a6100 0xc0000a6108
4) After the array is created, if no value is assigned, there is a default value. Numeric type array: The default value is 0. String array: The default value is "". Bool array: The default value is false (in fact, when the array is defined, the space has already been allocated. , just use the default value without assigning it)
5) Steps to use an array: 1. Declare the array and open up space 2. Assign a value to each element of the array ( not assigning a value means using the default zero value ) 3. Use the array
6) The subscripts of arrays start from 0.
7) Array subscripts must be used within the specified range, otherwise panic will be reported: array out of bounds, for example, var arr [5]int, the valid subscripts are 0-4
8) Go's array is a value type. By default, it is passed by value, so value copying will be performed and the arrays will not affect each other.
func Test(t [5]int) {
fmt.Printf("%p\n", &t)
}
c := [5]int{1, 2, 3, 4, 5}
fmt.Printf("%p\n", &c)
Test(c)
0xc00012a030
0xc00012a060
Note: [3]int is a data type, and length is also a data type. [3]int [4]int is not the same data type.
9) If you want to modify the original array in other functions, you can use reference transfer (pointer method) [Experience it first and draw a diagram]
func Test(t *[5]int) {
fmt.Printf("%p \n", t)
fmt.Println((*t)[0], (*t)[1], (*t)[2], (*t)[3], (*t)[4])
(*t)[0] = 100
}
func main() {
c := [5]int{1, 2, 3, 4, 5}
fmt.Printf("%p \n", &c)
Test(&c)
fmt.Println(c)
}
0xc00000e4e0
0xc00000e4e0
1 2 3 4 5
[100 2 3 4 5]
a *[3]int a represents a pointer to an array of type [3]int.
One is a value copy and the other is a pointer. If the data is very large, value copying is very resource-consuming.
If you only want to change the outer array when using an array, then use pointer transfer, which is efficient and fast.
The first one fails to compile: when the array is passed, the length is part of the type. Here, the array is sliced, and the compilation fails.
Second error: The length is part of the data type, the length is different, [3]int is different from the type [4]int
The third one is correct