Let's take a look at how to declare an array:
Copy Code code as follows:
Package Main
Import "FMT"
var arr [2]int//Declaration of an array
Func Main () {
ARR[0] = 1//array assignment
Fmt. Println (arr)
Arrtest: = [3]int{1, 2, 3}//array another way of declaring
Fmt. Println (Arrtest)
A: = [...] Int{1, 2}//[...] Automatically recognize the length of an array
Fmt. Println (a)
Fmt. Println (Len (a))//output array length
}
The go language can automatically calculate the length of an array, for example, you know that several arrays can be declared as follows
Copy Code code as follows:
Array of pointers
Copy Code code as follows:
a:=[3]int{1,2,3}
var p * [3]int = &a//This is an array of pointers we can see directly output pointers to arrays
X, y: =1, 3
A: = [...] *int{&x, &y}
Str. Println (a)//output such [0xc080000068 0xc080000070] address this is the array pointer
You can use the New keyword to declare
Copy Code code as follows:
P: = new ([10]int)
Fmt. PRINTLN (p)//&[0 0 0 0 0 0 0 0 0 0] Output a pointer
Multidimensional arrays are similar to other languages
Copy Code code as follows:
c: = [3][2]int{{1:2}, {2, 1}, {2, 2}}
Fmt. PRINTLN (c)//output [[0 2] [2 1] [2 2]]
Below is the declaration and use of slice in fact, this is a dynamic array
Copy Code code as follows:
Package Main
Import "FMT"
var arr [2]int//Declaration of an array
Func Main () {
ARR[0] = 1//array assignment
Fmt. Println (arr)
Arrtest: = [3]int{1, 2, 3}//array another way of declaring
Fmt. Println (Arrtest)
A: = [...] Int{1, 2}//[...] Automatically recognize the length of an array
Fmt. Println (a)
Fmt. Println (Len (a))//output array length
}
Take a look at the bubble algorithm go language version
Copy Code code as follows:
Package Main
Import "FMT"
Func Main () {
A: = [...] Int{3, 2, 5, 8, 6}
Fmt. Println (a)
Num: = Len (a)
For I: = 0; i < num; i++ {
For J: = i + 1; J < num; J + + {
If a[i] < A[j] {
Temp: = A[i]
A[i] = A[j]
A[J] = Temp
}
}
}
Fmt. Println (a)
}