An array of Golang foundations

Source: Internet
Author: User
Tags array definition array length

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:[email protected]
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, which T represents the type of each element. The number of elements? n ? is also part of that 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

The index of the array from the? 0 ? Start to go to? length - 1 ? End

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]}

In the above procedure, a the copy of the? is assigned to? b . In line 4th, b the first element of the? is changed to? Singapore . This will not be in the original array? a ? reflected in it.

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 changeLocal , and the array does not change because of a 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

By passing an array as a parameter to the? len ? function, you can get the length of the array. capcan 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

forA loop can be used to iterate over an element 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 ? Iterate through the elements in the array, from the index? 0 ? To? length of the array - 1

Go provides a better, more concise way to use the? for ? The loop? The rangemethod to iterate through the array. rangereturns 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 ? Use a For loop range method. It returns the index and the value at that index. We print these values and calculate the array? a ? The sum of all the elements in the

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 Array Advanced Usage 3.1 multi-dimensional array

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
    1. Array: is a fixed-length sequence of the same data type.

    2. The array definition:, var a [len]int For example: var a [5]int , the array length must be constant, and is part of the type. Once defined, the length cannot be changed.

    3. The length is part of the array type, so, var a[5] int and var a[10]int is a different type.

    4. The array can be accessed by subscript, the subscript is from 0 the beginning, the last element subscript is: len-1 . The usual operations for array indexing are as follows:

      for i := 0; i < len(a); i++ {   ...} for index, v := range a {   
    5. Access is out of bounds, if the subscript is outside the bounds of the array, triggering an access violation willpanic

    6. Arrays are value types, assignments, and delegates replicate the entire array instead of pointers. Therefore, changing the value of the copy does not change its value.

    7. the "= =", "! =" operators are supported because memory is always initialized.

    8. Pointer array [n]*T , array pointer *[n]T .

An array of Golang foundations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.