This is a creation in Article, where the information may have evolved or changed.
Arrays Array
- To define the format of an array: var
package mainimport ( "fmt")func main() { //数组的长度也是类型的一部分,因此具有不同长度的数组为不同类型 var a [2]int //定义长度为2的int型数组。 var b [1]int //长度为1的int型数组 b = a fmt.Println(b)//此时编译时不通过的}
- The length of the array is also part of the type, so arrays with different lengths are of different types
package mainimport ( "fmt")func main() { a := [20]int{19: 1} //长度为20的int型数组,索引位为19的赋值为1 b := [...]int{0: 1, 1: 2, 2: 3} //3个点代表不定长的数组,它会自己去推算数组的长度 fmt.Println(a) fmt.Println(b)}
- Note A pointer and pointer array that points to an array
package mainimport ( "fmt")func main() { x, y := 1, 2 c := [...]*int{&x, &y} //保存的元素是指向int型的指针 a := [...]int{99: 1} var p *[100]int = &a //指向数组的指针,取的是a的地址 //加*代表这是一个指针 fmt.Println(p) //打印的结果和a的结果是一样的,只不过前面多了一个取地址的符号 &,这就是指向数组的指针 fmt.Println(c) //指针数组,存的是x和y的内存地址}
- Array is a value type in Go
- You can use = = or! = to compare between arrays, but you cannot use < or >
package mainimport ( "fmt")func main() { a := [2]int{1, 2} b := [1]int{1} fmt.Println(a != b) //mismatched types [2]int and [1]int //a和b的长度也必须相同才能进行比较,长度不同代表类型不同,数组的比较也是比较严格的}
- You can use new to create an array, and this method returns a pointer to the array
package mainimport ( "fmt")func main() { p := new([10]int) //使用new关键字来创建这个数组的话,它返回的就是这个数组的指针 fmt.Println(p)}//结果PS G:\mygo\src\mytest> go run .\myfirst.go&[0 0 0 0 0 0 0 0 0 0]
package mainimport ( "fmt")func main() { a := [10]int{} a[1] = 2 fmt.Println(a) p := new([10]int) p[1] = 2 fmt.Println(p)}
- Go supports multidimensional arrays
package mainimport ( "fmt")func main() { a := [...][2]int{ {0: 1}, {1: 2}, } fmt.Println(a)}
- Bubble sort of Go language
Package Mainimport ("FMT") func main () {a: = [...] Int{5, 2, 3, 6, 7, 8, 9} 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)}