A basic demonstration of the use of arrays in the Go language
- 2020-05-30 20:22:20
- OfStack
First look at 1 to declare an array:
package main
import "fmt"
var arr [2]int // statement 1 An array
func main() {
arr[0] = 1 // Array assignment
fmt.Println(arr)
arrtest := [3]int{1, 2, 3} // An array of other 1 Kind of declaration
fmt.Println(arrtest)
a := [...]int{1, 2} //[...] Automatically identifies the length of the array
fmt.Println(a)
fmt.Println(len(a))// The length of the output array
}
The go language automatically calculates the length of an array, for example, if you know how many arrays can be declared as follows
a:=[...]int{1,2,3,45}
Pointer to an array
a:=[3]int{1,2,3}
var p * [3]int = &a // This is an array of Pointers We see that we can output Pointers to arrays directly
x , y :=1 ,3
a := [...]*int{&x ,&y}
str.Println(a) // This output [0xc080000068 0xc080000070] The address of the That's the pointer to the array
It can be declared using the new keyword
p := new([10]int)
fmt.Println(p) //&[0 0 0 0 0 0 0 0 0 0] The output 1 A pointer to the
Multidimensional arrays are like any other language
c := [3][2]int{{1: 2}, {2, 1}, {2, 2}}
fmt.Println(c) // The output [[0 2] [2 1] [2 2]]
Below is the declaration and use of slice which is essentially a dynamic array
package main
import "fmt"
var arr [2]int // statement 1 An array
func main() {
arr[0] = 1 // Array assignment
fmt.Println(arr)
arrtest := [3]int{1, 2, 3} // An array of other 1 Kind of declaration
fmt.Println(arrtest)
a := [...]int{1, 2} //[...] Automatically identifies the length of the array
fmt.Println(a)
fmt.Println(len(a))// The length of the output array
}
Take a look at the go language version of the bubble algorithm
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)
}