Golang arrays and slices

1, Array

Like most other languages, the array of Go language is also a fixed length sequence with the same element type.

(1) Array creation.

There are three ways to create arrays: [length]Type, [n] type {value1, Value2,..., valuen}, [...] Type {value1, Value2,..., valuen} is as follows:

func test5() {
    var iarray1 [5]int32
    var iarray2 [5]int32 = [5]int32{1, 2, 3, 4, 5}
    iarray3 := [5]int32{1, 2, 3, 4, 5}
    iarray4 := [5]int32{6, 7, 8, 9, 10}
    iarray5 := [...]int32{11, 12, 13, 14, 15}
    iarray6 := [4][4]int32{{1}, {1, 2}, {1, 2, 3}}
    fmt.Println(iarray1)
    fmt.Println(iarray2)
    fmt.Println(iarray3)
    fmt.Println(iarray4)
    fmt.Println(iarray5)
    fmt.Println(iarray6)
}

result:

[0 0 0 0 0]
[1 2 3 4 5]
[1 2 3 4 5]
[6 7 8 9 10]
[11 12 13 14 15]
[[1 0 0 0] [1 2 0 0] [1 2 3 0] [0 0 0 0]]

Let's look at the array iarray1, which only declares but does not assign a value. The Go language automatically assigns a value of 0 for us. Looking at iarray2 and iarray3, we can see that the declaration of Go language can indicate the type or not. var iarray3 = [5]int32{1, 2, 3, 4, 5} is also completely OK.

(2) The capacity and length of the array are the same. Both the cap() function and the len() function output the capacity (that is, the length) of the array. For example:

func test6() {
    iarray4 := [5]int32{6, 7, 8, 9, 10}
    fmt.Println(len(iarray4))
    fmt.Println(cap(iarray4))
}

The output is 5.

(3) Use:

func test7() {
    iarray7 := [5]string{"aaa", `bb`, "All right", "What do you want me to say", "()"}
    fmt.Println(iarray7)
    for i := range iarray7 {
        fmt.Println(iarray7[i])
    }
}

Output:

func test7() {
    iarray7 := [5]string{"aaa", `bb`, "All right", "What do you want me to say", "()"}
    fmt.Println(iarray7)
    for i := range iarray7 {
        fmt.Println(iarray7[i])
    }
}

2, Slice

In Go language, slices are the same sequence of elements with variable length and fixed capacity. The slicing essence of Go language is an array. The capacity is fixed because the length of the array is fixed. The capacity of the slice is the length of the hidden array. Variable length means variable within the range of array length.

(1) Slice creation.

There are four ways to create slices:

  1)make ( []Type ,length, capacity )

  2) make ( []Type, length)

  3) []Type{}

  4) []Type{value1 , value2 , ... , valueN }

As can be seen from 3) and 4), the only difference between creating a slice and creating an array is whether there is a number in "[]" before Type. If it is empty, it represents a slice, otherwise it represents an array. Because the length of the slice is variable. The following is an example of creating a slice:

func test8() {
    slice1 := make([]int32, 5, 8)
    slice2 := make([]int32, 9)
    slice3 := []int32{}
    slice4 := []int32{1, 2, 3, 4, 5}
    fmt.Println(slice1)
    fmt.Println(slice2)
    fmt.Println(slice3)
    fmt.Println(slice4)
}

Output is:

[0 0 0 0 0]
[0 0 0 0 0 0 0 0 0]
[]
[1 2 3 4 5]

As above, four slices, three empty slices and one valuable slice are created.

(2) Slice and hide arrays:

A slice is a reference to a hidden array, and the slice for that slice also references the same array. In the following example, a slice slice0 is created, and two slices slice1 and slic2 are created based on this slice:

func test9() {
    slice0 := []string{"a", "b", "c", "d", "e"}
    slice1 := slice0[2 : len(slice0)-1]
    slice2 := slice0[:3]
    fmt.Println(slice0, slice1, slice2)
    slice2[2] = "8"
    fmt.Println(slice0, slice1, slice2)
}

Output is:

[a b c d e] [c d] [a b c]
[a b 8 d e] [8 d] [a b 8]

It can be seen that slice0, slice1 and slice2 are references to the same underlying array, so slice2 changes and the other two will change.

(3) Traverse and modify slices:

func test10() {
    slice0 := []string{"a", "b", "c", "d", "e"}
    fmt.Println("\n~~~~~~Element traversal~~~~~~")
    for _, ele := range slice0 {
        fmt.Print(ele, " ")
        ele = "7"
    }
    fmt.Println("\n~~~~~~Index traversal~~~~~~")
    for index := range slice0 {
        fmt.Print(slice0[index], " ")
    }
    fmt.Println("\n~~~~~~Element indexes are used together~~~~~~")
    for index, ele := range slice0 {
        fmt.Print(ele, slice0[index], " ")
    }
    fmt.Println("\n~~~~~~modify~~~~~~")
    for index := range slice0 {
        slice0[index] = "9"
    }
    fmt.Println(slice0)
}

As mentioned above, the first three loops use different for range loops. When there are two elements after for and before range, the first element represents the index and the second element represents the element value. Use "" Is ignored because unused values in the go language cause compilation errors.

When there is only one element, the element represents the index.

An element can only be modified with an index. For example, in the first traversal, the assignment ele is 7, and the result has no effect. In the element traversal, ele is the value transfer, and ele is the copy of the slice element. Modifying it will not affect the original value. In the fourth traversal - index traversal, the value referenced by the slice element is modified, so it can be modified.

The result is:

~~~~~~Element traversal~~~~~~
a b c d e 
~~~~~~Index traversal~~~~~~
a b c d e 
~~~~~~Element indexes are used together~~~~~~
aa bb cc dd ee 
~~~~~~modify~~~~~~
[9 9 9 9 9]

(4) , append, copy slice:

func test11() {
    slice := []int32{}
    fmt.Printf("slice The length of the is:%d,slice Is:%v\n", len(slice), slice)
    slice = append(slice, 12, 11, 10, 9)
    fmt.Printf("After addition, slice The length of the is:%d,slice Is:%v\n", len(slice), slice)
    slicecp := make([]int32, (len(slice)))
    fmt.Printf("slicecp The length of the is:%d,slicecp Is:%v\n", len(slicecp), slicecp)
    copy(slicecp, slice)
    fmt.Printf("After copying the assignment, slicecp The length of the is:%d,slicecp Is:%v\n", len(slicecp), slicecp)
}

The built-in functions append and copy are used to append and copy slices. The copy function returns the number of last copied elements.

(5) . built in function append

The built-in function append can append one or more other values of the same type to a slice. If the number of additional elements exceeds the original slice capacity, the last returned is a new slice in a new array. If it does not exceed, the last returned is the new slice in the original array. In any case, append has no effect on the original slice. Examples are as follows:

func test12() {
    slice := []int32{1, 2, 3, 4, 5, 6}
    slice2 := slice[:2]
    _ = append(slice2, 50, 60, 70, 80, 90)
    fmt.Printf("slice Is:%v\n", slice)
    fmt.Printf("Slice for operation:%v\n", slice2)
    _ = append(slice2, 50, 60)
    fmt.Printf("slice Is:%v\n", slice)
    fmt.Printf("Slice for operation:%v\n", slice2)
}

As mentioned above, the append method is used twice, and the results returned are completely different because the number of elements added by the append method does not exceed the capacity of slice. In any case, the original slice slice2 had no effect. result:

slice Is:[1 2 3 4 5 6]
Slice for operation:[1 2]
slice Is:[1 2 50 60 5 6]
Slice for operation:[1 2]

Keywords: Go

Added by kaspari22 on Mon, 10 Jan 2022 09:21:09 +0200