Article reproduced please specify the source www.leexide.com
Hope that each of the friends who seek to reprint can be carried out in accordance with the requirements, to encourage original, respect for the original.
Public number: DevOps Operation home
QQ Number: 1045884038
E-mail:leexide@126.com
If you have any questions or suggestions, please follow the public number
1 Introduction to Arrays
An array is a collection of elements of the same type. For example, an integer set of 5,8,9,79,76 forms an array. Mixing different types of elements, such as arrays containing strings and integers, is not allowed in the Go language. (Note: Of course, if it is an array of type interface{}, it can contain any type).
2 Common operations for arrays
The representation of an array is [n]T
. n
represents the number of elements in an array, T
representing the type of each element. The number of elements n
is also part of the type.
2.1 Array Initialization
One-dimensional arrays are initialized as follows
func main() { var a [4]int //元素自动初始化为零[0 0 0 0] b := [4]int{2, 5} //未提供初始化值得元素自动初始化为0 [2 5 0 0] c := [4]int{5, 3: 10} //可指定索引位置初始化 [5 0 0 10] d := [...]int{1, 2, 3} //编译器按初始化值数量确定数组长度 [1 2 3] e := [...]int{10, 3: 100} //支持索引初始化,但注意数组长度与此有关 [10 0 0 100] fmt.Println(a, b, c, d, e)}
For composite types such as structs, you can omit element initialization type labels
package mainimport "fmt"func main() { type user struct { name string age byte } d := [...]user{ {"tom", 20},// 可省略元素类型。 {"lee", 18},// 别忘了最后一行的逗号。 } fmt.Printf("%#v\n", d)}/*output[2]main.user{main.user{name:"tom", age:0x14}, main.user{name:"lee", age:0x12}}*/
When defining a multidimensional array, only the first dimension allows the use of "..."
package mainimport "fmt"func main() { a := [2][2]int{ {1, 2}, {3, 4}, } b := [...][2]int{ {10, 20}, {30, 40}, } c := [...][2][2]int{ //三维数组 { {1, 2}, {3, 4}, }, { {10, 20}, {30, 40}, }, } fmt.Println(a) //[[1 2] [3 4]] fmt.Println(b) //[[10 20] [30 40]] fmt.Println(c) //[[[1 2] [3 4]] [[10 20] [30 40]]]}
Multidimensional array Definitions
package mainimport ( "fmt")var arr0 [5][3]intvar arr1 [2][3]int = [...][3]int{{1, 2, 3}, {7, 8, 9}}func main() { a := [2][3]int{{1, 2, 3}, {4, 5, 6}} b := [...][2]int{{1, 1}, {2, 2}, {3, 3}} // 第 2 纬度不能用 "..."。 fmt.Println(arr0, arr1) fmt.Println(a, b)}/*output[[0 0 0] [0 0 0] [0 0 0] [0 0 0] [0 0 0]] [[1 2 3] [7 8 9]][[1 2 3] [4 5 6]] [[1 1] [2 2] [3 3]] */
2.2 Array index
Index of an array from 0
start to length - 1
finish
func main() { var a [3]int //int array with length 3 a[0] = 12 // array index starts at 0 a[1] = 78 a[2] = 50 fmt.Println(a)}
2.3 Array is a value type
The array in Go is a value type and not a reference type. This means that when an array is assigned to a new variable, the variable gets a copy of the original array. If you make changes to a new variable, the original array is not affected.
func main() { a := [...]string{"USA", "China", "India", "Germany", "France"} b := a // a copy of a is assigned to b b[0] = "Singapore" fmt.Println("a is ", a) //a is [USA China India Germany France] fmt.Println("b is ", b) //b is [Singapore China India Germany France]}
a
the copy of the above program is assigned b
. In line 4th, b
the first element is changed to Singapore
. This is not reflected in the original array a
.
Similarly, when an array is passed as a parameter to a function, they are passed by value, while the original array remains unchanged.
package mainimport "fmt"func changeLocal(num [5]int) { num[0] = 55 fmt.Println("inside function ", num)}func main() { num := [...]int{5, 6, 7, 8, 8} fmt.Println("before passing to function ", num) changeLocal(num) //num is passed by value fmt.Println("after passing to function ", num)}/*outputbefore passing to function [5 6 7 8 8]inside function [55 6 7 8 8]after passing to function [5 6 7 8 8]*/
In the 13 lines of the above program, the array num
is actually passed to the function by value, and the changeLocal
array does not change because of the function call.
The value copy behavior can cause performance problems, and it is generally recommended to use slice, or array pointers.
package mainimport ( "fmt")func test(x [2]int) { fmt.Printf("x: %p\n", &x) x[1] = 1000}func main() { a := [2]int{} fmt.Printf("a: %p\n", &a) test(a) fmt.Println(a)}/*output:a: 0xc042062080x: 0xc0420620c0[0 0] */
2.4 Number of team leader degrees and number of elements
len
you can get the length of the array by passing the array as an argument to the function. cap
can get the number of elements
package mainimport "fmt"func main() { a := [...]float64{67.7, 89.8, 21, 78} fmt.Println("length of a is", len(a)) //length of a is 4 fmt.Println("num of a is",cap(a)) //num of a is 4}
Note: Both the built-in function Len and the CAP return the first dimension length
package mainfunc main() { a := [2]int{} b := [...][2]int{ {10, 20}, {30, 40}, {50, 60}, } println(len(a), cap(a)) // 2 2 println(len(b), cap(b)) // 3 3 println(len(b[1]), cap(b[1])) // 2 2}
# # # #2.5 use range to iterate over algebraic groups
for
Loops can be used to iterate over the elements in an array.
package mainimport "fmt"func main() { a := [...]float64{67.7, 89.8, 21, 78} for i := 0; i < len(a); i++ { // looping from 0 to the length of the array fmt.Printf("%d th element of a is %.2f\n", i, a[i]) }}
The above program uses for
loops to iterate through the elements in the array, from index 0
to length of the array - 1
Go provides a better, more concise way to for
iterate through an array by using the loop's range method. range
returns the index and the value at that index. Let's rewrite the above code using range. We can also get the sum of all the elements in the array.
package mainimport "fmt"func main() { a := [...]float64{67.7, 89.8, 21, 78} sum := float64(0) for i, v := range a { //range returns both the index and value fmt.Printf("%d the element of a is %.2f\n", i, v) sum += v } fmt.Println("\nsum of all elements of a", sum)}
The 8th line of the above procedure for i, v := range a
uses the For loop range method. It returns the index and the value at that index. We print these values and calculate a
the sum of all the elements in the array.
If you only need the value and want to ignore the index, you can do so by replacing the index with a _
blank identifier.
for _, v := range a { // ignores index }
The For loop above ignores the index, and the same value can be ignored.
2.6 Array operator operation
If the element type supports the "==,!=" operator, the array also supports this operation
package mainfunc main() { var a, b [2]int println(a == b) //true c := [2]int{1, 2} d := [2]int{0, 1} println(c != d) //true /* var e, f [2]map[string]int println(e == f) //invalid operation: e == f ([2]map[string]int cannot be compared) */}
3 Advanced usage of arrays
3.1 Multi-dimensional arrays
The arrays we created so far are all one-dimensional, and the Go language can create multidimensional arrays.
package mainimport ( "fmt")func printArray(a [3][2]string) { for _, v1 := range a { for _, v2 := range v1 { fmt.Printf("%s ", v2) } fmt.Printf("\n") }}func main() { a := [3][2]string{ {"lion", "tiger"}, {"cat", "dog"}, {"pigeon", "peacock"}, // this comma is necessary. The compiler will complain if you omit this comma } printArray(a) var b [3][2]string b[0][0] = "apple" b[0][1] = "samsung" b[1][0] = "microsoft" b[1][1] = "google" b[2][0] = "AT&T" b[2][1] = "T-Mobile" fmt.Printf("\n") printArray(b)}/*outputlion tiger cat dog pigeon peacock apple samsung microsoft google AT&T T-Mobile */
Multidimensional Array traversal
package mainimport ( "fmt")func main() { var f [2][3]int = [...][3]int{{1, 2, 3}, {7, 8, 9}} for k1, v1 := range f { for k2, v2 := range v1 { fmt.Printf("(%d,%d)=%d ", k1, k2, v2) } fmt.Println() }}/*output:(0,0)=1 (0,1)=2 (0,2)=3 (1,0)=7 (1,1)=8 (1,2)=9 */
3.2 Array pointers and arrays of pointers
To distinguish between pointer arrays and array pointers. An array of pointers is an array of pointer types, and an array pointer is an address that gets an array variable.
package mainimport "fmt"func main() { x, y := 10, 20 a := [...]*int{&x, &y} p := &a fmt.Printf("%T,%v\n", a, a) //[2]*int,[0xc042062080 0xc042062088] fmt.Printf("%T,%v\n", p, p) //*[2]*int,&[0xc042062080 0xc042062088]}
can get any element address
func main() { a := [...]int{1, 2} println(&a, &a[0], &a[1]) //0xc042049f68 0xc042049f68 0xc042049f70}
Array pointers can be used to manipulate elements directly
func main() { a := [...]int{1, 2} p := &a p[1] += 10 println(p[1]) //12}
4 Arrays Use common pits
When defining an array type, the array length must be a non-negative integer constant expression, and the length is the type component. That is, the element types are the same, but arrays of different lengths do not belong to the same type.
Example:
func main() { var d1 [3]int var d2 [2]int d1 = d2 //cannot use d2 (type [2]int) as type [3]int in assignment}
5 Summary of the array
-
Array: is a fixed-length sequence of the same data type.
-
Array definition: var a [len]int
, for example: var a [5]int
, the length of the array must be constant, and is part of the type. Once defined, the length cannot be changed. The
-
Length is part of the array type, so var a[5] int
and var a[10]int
are different types. The
-
Array can be accessed by subscript, starting with 0
and the last element subscript: len-1
. The usual operations for an array index are as follows:
for I: = 0; i < Len (a); i++ {...} for index, V: = Range A {...}
-
Access is out of bounds, if the subscript is outside the bounds of the array, then the access is triggered, panic
- Arrays are value types, assignments and delegates replicate the entire array, not pointers. Therefore, changing the value of the copy does not change its value.
-
Supports the "= =", "! =" operators because memory is always initialized.
- pointer array
[n]*t
, array pointer *[n]t
.