An array of

An array is a set of numeric data sequences of the same type and fixed length. Because arrays in GO are of the same type and of fixed length, these two characteristics are reflected in the declaration of arrays.

var array [5]int // [0 0 0 0 0]
Copy the code

The array is declared by [SIZE] (array length in square brackets) plus TYPE (TYPE). The above code indicates that the array variable is of length 5 and all five data types are int.

The default value of int is 0, so array is [0 0 0 0 0].

Array initialization

In the initialization phase, you specify the value of each position in the array as {}.

var array [3]int = [3]int{1.2.3} / / [1 2 3]
Copy the code

It can be seen that {} should also be preceded by the length and type of the array. Because go can carry out type derivation, the type declared after the variable appears a little redundant and can be omitted.

var array = [3]int{1.2.3} / / [1 2 3]
Copy the code

🎶 Specifies index assignment

During initialization, we can also specify the index for assignment, that is, we don’t have to assign a specific value to each position in the array.

var array = [5]int{1: 77.3: 77} // [0 77 0 77 0]
Copy the code

The array above outputs: [0 77 0 77 0]. As in other languages, arrays are indexed from 0, and we specify 77 for index 1 and index 3. The rest of the values are the default values for their types, since they are not specified.

🎶 automatically derives the array length

The previous examples specify the length of the array, in fact, we can use […] Tells the GO compiler that the length of the array is undetermined and cannot be determined until initialization, and then go deducts it automatically at compile time.

var array = [...]int{1.2.3.4.5} // [1 2 3 4 5]
fmt.Println("array length is".len(array))
Copy the code

We can get the length of the array by using len, which looks like this:

If we assign the value at the specified index, the final length depends on the last index. In the following code, we specify that index 5 is 77, so the array length is 6.

var array = [...]int{1: 77.5: 77} // [0 77 0 0 0 77]
fmt.Println("array length is".len(array))
Copy the code

Assignment and access

As in other languages, arrays are assigned and accessed through the [Index] operation.

var array = [...]int{1.2.3}
array[0] = 100 // Reassign the position of index 0 to 100
fmt.Println("array is", array)
Copy the code

We now implement a function that averages the array:

func getAverage(array [5]int) float32 {
	var sum int
	var avg float32

	for i := 0; i < 5; i++ {
		sum += array[i]
	}

	avg = float32(sum) / 5

	return avg
}
Copy the code
var array = [5]int{1.2.3.4.5}
fmt.Println("average is", getAverage(array))
Copy the code

Multidimensional array

The declaration of a multidimensional array, as opposed to a one-dimensional array, is how many [SIZE] are in front of it.

var a1 [2] [3]int // A two-dimensional array
var a1 [2] [3] [4]int // Three dimensional array
Copy the code

Take a three-dimensional array. The number in the first [] represents the length of the outermost array, and so on. [2][3][4]int Indicates that the outermost array is of length 2, the second layer array is of length 3, and the innermost array is of length 4. The assignment is the same as for one-dimensional arrays, except that multi-dimensional arrays require multiple {} to be nested.

var a1 = [2] [3] [4]int{{{1.2.3.4},
    {1.2.3.4},
    {1.2.3.4}}, {{1.2.3.4},
    {1.2.3.4},
    {1.2.3.4},
  },
}
fmt.Println(a1)
Copy the code

Print result:

Multi-dimensional arrays are accessed through the same [] + array index as one-dimensional arrays, except that multi-dimensional arrays require multiple [] to access a value.

If we want to get the 2 in the figure below, the access is: array[0][1][1]

fmt.Println("array[0][1][1] = ", array[0] [1] [1])
Copy the code

slice

As mentioned above, an array is a set of data sets of the same type and fixed length, while a slice is a relatively abstract array, whose length is not fixed and declared in a similar way to an array ([] does not indicate the length of the array, and does not use […]). Length derivation) :

var slice []int
Copy the code

Slice initialization

The initialization of slices is similar to that of arrays, as long as the array length indicated in [] is omitted:

var s1 = []int{1.2.3}
s2 := []int{1.2.3} / / short
Copy the code

In addition to this declaration of literals, slices can be initialized using go’s built-in make method:

var s1 = make([]int.3)
s2 := make([]int.3) / / short
Copy the code

The second argument to the make method indicates the length of the slice. Although the length of the slice is variable, you need to specify a length when creating a slice using the make method. In addition to specifying the length of the slice, the make method also supports passing in a third parameter that specifies the “size” of the slice. If the size of the slice is not specified, the size of the initial state slice is the same as the length.

func make([]T, len.cap)
Copy the code

Length and capacity

Length refers to how many elements are in the slice, while capacity can be understood as how much space is created in memory by the current slice. As described earlier, you can get the length of an array using the Len method. You can also get the length of a slice using this method. To obtain the capacity of a slice, use the CAP method.

s1 := make([]int.5)
fmt.Printf("The length of s1 is %d\n".len(s1))
fmt.Printf("The capacity of s1 is %d\n".cap(s1))
Copy the code

It can be seen that in the initial state, the length of the slice is consistent with the capacity. If you want to change the length of the slice, append a new value to the end of the slice using the append method.

s1 := make([]int.3.5) // Declare a section of length 3 and capacity 5
s1 = append(s1, 1) // Add a value to the tail, and the length becomes 4

fmt.Printf("The length of s1 is %d\n".len(s1))
fmt.Printf("The capacity of s1 is %d\n".cap(s1))
Copy the code

The append method can accept multiple arguments. After appending a value, we continue to call the Append method and append two more values to the slice:

s1 := make([]int.3.5)
s1 = append(s1, 1)
s1 = append(s1, 2.3)
fmt.Println(s1) // [0 0 0 1 2 3]
fmt.Printf("The length of s1 is %d\n".len(s1))
fmt.Printf("The capacity of s1 is %d\n".cap(s1))
Copy the code

At this time, the length of the slice has become 6, which exceeds the capacity of the slice. Will the capacity of the switch also become 6 at this time?

According to the output result, the capacity of the slice now becomes 10, which means that the expansion of the capacity of the slice is doubled on the basis of the previous operation. To test this conclusion, we append 5 values after the slice to make the slice length 11, beyond the current capacity, and see what the capacity becomes.

s1 := make([]int.3.5)
s1 = append(s1, 1)
s1 = append(s1, 2.3)
s1 = append(s1, 4.5.6.7.8)

fmt.Printf("The length of s1 is %d\n".len(s1))
fmt.Printf("The capacity of s1 is %d\n".cap(s1))
Copy the code

It can be seen that the capacity of the slice becomes 20, which also verifies our previous conclusion that when the length of the slice exceeds its capacity, the capacity will double on the original basis. So if the slice capacity reaches 2000 and the length exceeds 2000, does the slice capacity also become 4000?

s1 := make([]int.1024)
s1 = append(s1, 1)

fmt.Printf("\nThe length of s1 is %d\n".len(s1))
fmt.Printf("The capacity of s1 is %d\n".cap(s1))
Copy the code

It can be seen that our newly defined slice length is 1024, and the capacity does not double when the length becomes 1025. To avoid endless expansion of slice capacity, GO specifies that if the current slice length is greater than 1024, only 25% of the capacity will be increased when the length exceeds its capacity.

Slice the interception

A slice is called a slice because it can be created by cutting out a chunk of an array. The syntax is simple: Array[start:end].

arr := [5]int{1.2.3.4.5}
slice := arr[1:3]

fmt.Println(slice) / / [2, 3]
Copy the code

Arr [1:3] truncates the array from index 1 all the way to index 3 (excluding 3) to form a slice. And of course the beginning and the end of the number can also be omitted, if we if we omit the beginning that means that we intercept at the beginning zero, and omit the end that means that we intercept at the end all the way to the end of the array.

arr := [5]int{1.2.3.4.5}
slice := arr[1:]
fmt.Println(slice) // [2 3 4 5]
Copy the code

By omitting the beginning and end of the cut, we can make a copy of an array and form a slice. (PS. The new data formed by the interception operation is a slice)

arr := [5]int{1.2.3.4.5}
slice := arr[:]

fmt.Printf("slice = %v, slice type is %T", slice, slice)
Copy the code