This is the 7th day of my participation in Gwen Challenge

Hi, I’m @Luo Zhu

This article was first published on luo Zhu’s official website

This article was translated from Golang Tutorial Series

This article synchronizes in the public account “luo Zhu early teahouse”, reprint please contact the author.

Creation is not easy, form a habit, quality three even!

>>> <<<

An array is a collection of elements belonging to the same type. For example, the set of integers 5, 8, 9, 79, 76 form an array. Mixing different types of values is not allowed in Go, such as arrays containing both strings and integers.

The array declaration

Arrays belong to type [n]T. N represents the number of elements in the array, and T represents the type of each element. The number n of elements is also part of a type (we’ll discuss this in more detail later).

There are different ways to declare arrays. Let’s look at them one by one.

package main

import (
    "fmt"
)

func main(a) {
    var a [3]int // An array of length 3
    fmt.Println(a)
}
Copy the code

Run in playground

Var a[3]int Declares an array of integers of length 3. All elements in an array are automatically assigned a zero value of array type. In this case, A is an array of integers, so all elements of A are assigned to 0, the zero value of int. Running the above program prints

[0 0 0]
Copy the code

The index of the array starts at 0 and ends at Length-1. Let’s assign some values to the array above.

package main

import (
    "fmt"
)


func main(a) {
    var a [3]int // An int array of length 3
    a[0] = 12 // The array index starts at 0
    a[1] = 78
    a[2] = 50
    fmt.Println(a)
}
Copy the code

Run in playground

A [0] assigns the first element of the array. The program will print

78 50 [12]Copy the code

Let’s create the same array using a short declaration.

package main

import (
    "fmt"
)

func main(a) {
    a := [3]int{12.78.50} // Create a short declaration for the array
    fmt.Println(a)
}
Copy the code

Run in playground

The above program will print the same output

78 50 [12]Copy the code

With short declarations, you don’t have to assign a value to all the elements in an array.

package main

import (
    "fmt"
)

func main(a) {
    a := [3]int{12}
    fmt.Println(a)
}
Copy the code

Run in playground

In the above program, a := [3]int{12} declares an array of length 3, but only provides a value of 12. The remaining two elements are automatically assigned 0. The program will print

0 0 [12]Copy the code

You can even ignore the length of the array in the declaration and use… Replace it and let the compiler calculate the length automatically. The code implementation is as follows.

package main

import (
    "fmt"
)

func main(a) {
    a := [...]int{12.78.50} / /... Let the compiler determine the length of the array
    fmt.Println(a)
}
Copy the code

Run in playground

The size of the array is part of the type. So [5]int and [25]int are different types. Therefore, you cannot resize the array. Don’t worry about this limitation, because you can use slicing to get around it.

package main

func main(a) {
    a := [3]int{5.78.8}
    var b [5]int
    b = a // Cannot be true because '[3]int' and '[5]int' are different types
}
Copy the code

Run in playground

In the above program, we tried to assign a variable of type [3]int to a variable of type [5]int, which is not allowed, so the compiler prints the following error

./prog.go:6:7: cannot use a (type [3]int) as type [5]int in assignment
Copy the code

Arrays are value types

Arrays in Go are value types rather than reference types. This means that when they are assigned to a new variable, a copy of the original array is assigned to the new variable. If a change is made to the new variable, it will not be reflected in the original array.

package main

import "fmt"

func main(a) {
    a := [...]string{"USA"."China"."India"."Germany"."France"}
    b := a // The copy of A is assigned to B
    b[0] = "Singapore" // The first element of B is changed to Singapore, which does not affect A
    fmt.Println("a is ", a)
    fmt.Println("b is ", b)
}
Copy the code

Run in playground

The program will print:

a is [USA China India Germany France]
b is [Singapore China India Germany France]
Copy the code

Similarly, when arrays are passed to functions as arguments, they are passed by value, leaving the original array unchanged.

package main

import "fmt"

func changeLocal(num [5]int) {
    num[0] = 55
    fmt.Println("inside function ", num)

}
func main(a) {
    num := [...]int{5.6.7.8.8}
    fmt.Println("before passing to function ", num)
    changeLocal(num) // num is passed by value and therefore does not change due to function calls
    fmt.Println("after passing to function ", num)
}
Copy the code

Run in playground

The program will print:

before passing to function  [5 6 7 8 8]
inside function  [55 6 7 8 8]
after passing to function  [5 6 7 8 8]
Copy the code

The length of the array

The length of the array is obtained by passing the array as an argument to len.

package main

import "fmt"

func main(a) {
    a := [...]float64{67.7.89.8.21.78}
    fmt.Println("length of a is".len(a))
}
Copy the code

Run in playground

The program above will print out

length of a is 4
Copy the code

Use range to iterate over an array

The for loop can be used to iterate over the elements of an array.

package main

import "fmt"

func main(a) {
    a := [...]float64{67.7.89.8.21.78}
    for i := 0; i < len(a); i++ { // Loop from 0 to the length of the array
        fmt.Printf("%d th element of a is %.2f\n", i, a[i])
    }
}
Copy the code

Run in playground

The above program uses a for loop to iterate over the elements of the array, from index 0 to length of the array-1. The program works and prints

0 th element of a is 67.70
1 th element of a is 89.80
2 th element of a is 21.00
3 th element of a is 78.00
Copy the code

Go provides a better, cleaner way to iterate over arrays by using the range form of the for loop. Range returns the index and the value at that index. Let’s rewrite the above code using range. We will also find the sum of all the elements of the array.

package main

import "fmt"

func main(a) {
    a := [...]float64{67.7.89.8.21.78}
    sum := float64(0)
    for i, v := range a { // range returns both the index and the value
        fmt.Printf("%d the element of a is %.2f\n", i, v)
        sum += v
    }
    fmt.Println("\nsum of all elements of a",sum)
}
Copy the code

Run in playground

We print the values and sum up all the elements of array A. The output of the program is,

2 The element of a is 21.00 3 the element of a is 78.00 sum of All elements of a 256.5Copy the code

If you only want this value and want to ignore the index, you can do so by replacing the index with the _ blank identifier.

for _, v := range a { // Ignore the index
}
Copy the code

The for loop above ignores the index. Again, the value can be ignored.

Multidimensional array

The arrays we’ve created so far have been one-dimensional. We can create multi-dimensional arrays.

package main

import (
    "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) {
    a := [3] [2]string{{"lion"."tiger"},
        {"cat"."dog"},
        {"pigeon"."peacock"}, // This comma is required. If you omit the comma, the compiler will report an error
    }
    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)
}
Copy the code

Run in playground

The program above will print:

lion tiger
cat dog
pigeon peacock

apple samsung
microsoft google
AT&T T-Mobile
Copy the code

That’s the array. Although arrays seem flexible enough, they are limited by a fixed length. Unable to increase array length. And that’s what slicing is good at. In fact, slicing is more common in Go than traditional arrays.

conclusion

Concern public account Luo Zhu early teahouse, a place to continue to share programming knowledge.

  • give a likeIs equal to learning,Looking at theIs equal to the master
  • Finally, I wish you all 2021 study progress, promotion and salary increase