“This is the fourth day of my participation in the First Challenge 2022. For details: First Challenge 2022”
1. Arrays and slices
1.1 What is an Array
The Go language provides array-type data structures. An array is a sequence of numbered, fixed-length data items of the same unique type, which can be any primitive type such as an integer, a string, or a custom type.
Array elements can be read (or modified) by indexes (positions), starting at 0, with the first element indexed at 0, the second at 1, and so on. Array subscripts range from 0 to length minus 1.
Once an array is defined, its size cannot be changed.
1.2 Syntax for arrays
Declare and initialize arrays
You need to specify the size of the array and the type of data to store.
var variable_name [SIZE] variable_type
Copy the code
Sample code:
var balance [10] float32
var balance = [5]float32{1000.0.2.0.3.4.7.0.50.0}
Copy the code
The number of elements in {} cannot be greater than the number in []. If you ignore the numbers in [] and do not set the array size, Go will set the array size based on the number of elements:
var balance = []float32{1000.0.2.0.3.4.7.0.50.0}
balance[4] = 50.0
Copy the code
Other ways to create arrays:
var a [4] float32 Var arr2 = [4]float32{}
fmt.Println(a) // [0 0 0 0]
var b = [5] string{"ruby"."King two Dogs"."rose"}
fmt.Println(b) // [Ruby]
var c = [5] int{'A'.'B'.'C'.'D'.'E'} // byte
fmt.Println(c) // [65 66 67 68 69]
d := [...] int{1.2.3.4.5}// Set the size of the array according to the number of elements
fmt.Println(d)//[1 2 3 4 5]
e := [5] int{4: 100} // [0 00 0 100]
fmt.Println(e)
f := [...] int{0: 1.4: 1.9: 1} // [1 0 0 0 1 0 0 0 1]
fmt.Println(f)
Copy the code
2. Array traversal
2.1 Access to array elements
Accessing an array element
float32 salary = balance[9]
Copy the code
Sample code:
package main
import "fmt"
func main(a) {
var n [10]int /* n is an array of length 10 */
var i,j int
/* Initializes elements for array n */
for i = 0; i < 10; i++ {
n[i] = i + 100 /* Sets the element to I + 100 */
}
/* Prints the value of each array element */
for j = 0; j < 10; j++ {
fmt.Printf("Element[%d] = %d\n", j, n[j] )
}
}
Copy the code
Running results:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Copy the code
2.2 Array length
We get the length of the array by passing it as an argument to len.
Sample code:
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
Running results:
length of a is 4
Copy the code
You can even ignore the length of the array in the declaration and replace it with… Let the compiler find the length for you. This is done in the following program.
Sample code:
package main
import (
"fmt"
)
func main(a) {
a := [...]int{12.78.50} // ... makes the compiler determine the length
fmt.Println(a)
}
Copy the code
2.3. Go through the number group
package main
import "fmt"
func main(a) {
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])
}
}
Copy the code
2.4 the for… The range traversal
Use range to iterate over groups of numbers:
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 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
If you just need the value and want to ignore the index, you can do so by replacing the index with the _ blank identifier.
for _, v := range a { //ignores index
}
Copy the code
3. Arrays are value types
Arrays in Go are value types, not 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 changes are made to a new variable, they are not reflected in the original array.
package main
import "fmt"
func main(a) {
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)
fmt.Println("b is ", b)
}
Copy the code
Running results:
a is [USA China India Germany France]
b is [Singapore China India Germany France]
Copy the code
The size of the array is part of the type. So [5]int and [25]int are different types. Therefore, arrays cannot be resized. Don’t worry about this limitation, because slicing exists to solve this problem.
package main
func main(a) {
a := [3]int{5.78.8}
var b [5]int
b = a //not possible since [3]int and [5]int are distinct types
}
Copy the code
4. Preliminary use of Slice
4.1 What is Slicing
Go slicing is an abstraction of arrays. The length of Go arrays cannot be changed, and such collections are not suitable for certain scenarios. Go provides a flexible and powerful built-in type slice (” dynamic array “). Compared with arrays, the length of slices is not fixed, and you can append elements, which may increase the size of slices
Slicing is a convenient, flexible and powerful wrapper. The slice itself does not have any data. They are just references to existing arrays.
Compared with array, slice does not need to set the length and does not need to set the value in [], which is relatively free
Conceptually, slice is like a structure that contains three elements:
- Pointer to the starting position specified by slice in the array
- Length, the length of slice
- Maximum length, which is the length from the start of slice to the end of the array
4.2 Syntax of slicing
Definition section
var identifier []type
Copy the code
Slices need not specify length. Or use the make() function to create slices:
var slice1 []type = make([]type.len) can also be abbreviated slice1 :=make([]type.len)
make([]T, length, capacity)
Copy the code
Initialize the
s[0] = 1
s[1] = 2
s[2] = 3
s :=[] int {1.2.3 }
s := arr[startIndex:endIndex]
Copy the code
Create a new slice (front closed and back open) of the elements in arR from subscript startIndex to endIndex-1 with length endindex-startIndex
s := arr[startIndex:]
Copy the code
By default, endIndex represents the last element up to arR
s := arr[:endIndex]
Copy the code
The default startIndex will start with the first element of the ARR
package main
import (
"fmt"
)
func main(a) {
a := [5]int{76.77.78.79.80}
var b []int = a[1:4] //creates a slice from a[1] to a[3]
fmt.Println(b)
}
Copy the code
4.3 Modifying section
Slice does not have any data of its own. It’s just a representation of the underlying array. Any changes made to slice are reflected in the underlying array. Sample code:
package main
import (
"fmt"
)
func main(a) {
darr := [...]int{57.89.90.82.100.78.67.69.59}
dslice := darr[2:5]
fmt.Println("array before",darr)
for i := range dslice {
dslice[i]++
}
fmt.Println("array after",darr)
}
Copy the code
Running results:
array before [57 89 90 82 100 78 67 69 59]
array after [57 89 91 83 101 78 67 69 59]
Copy the code
When multiple slices share the same underlying array, changes made to each element are reflected in the array.
Sample code:
package main
import (
"fmt"
)
func main(a) {
numa := [3]int{78.79 ,80}
nums1 := numa[:] //creates a slice which contains all elements of the array
nums2 := numa[:]
fmt.Println("array before change 1",numa)
nums1[0] = 100
fmt.Println("array after modification to slice nums1", numa)
nums2[1] = 101
fmt.Println("array after modification to slice nums2", numa)
}
Copy the code
Running results:
array before change 1 [78 79 80]
array after modification to slice nums1 [100 79 80]
array after modification to slice nums2 [100 101 80]
Copy the code
5. Length and capacity of slices
5.1 Len () and Cap () functions
The length of a slice is the number of elements in the slice. The size of a slice is the number of elements in the underlying array starting with the index on which the slice was created.
Slices are indexable and length slices can be obtained by len() method provides a method for calculating the capacity cap() can measure how long slices can reach
package main
import "fmt"
func main(a) {
var numbers = make([]int.3.5)
printSlice(numbers)
}
func printSlice(x []int){
fmt.Printf("len=%d cap=%d slice=%v\n".len(x),cap(x),x)
}
Copy the code
The results
len=3 cap=5 slice=[0 0 0]
Copy the code
5.2 the empty section
A slice defaults to nil with a length of 0 until initialized
package main
import "fmt"
func main(a) {
var numbers []int
printSlice(numbers)
if(numbers == nil){
fmt.Printf("The slice is empty.")}}func printSlice(x []int){
fmt.Printf("len=%d cap=%d slice=%v\n".len(x),cap(x),x)
}
Copy the code
The results
len=0 cap=0Slice =[] The slice is emptyCopy the code
package main
import "fmt"
func main(a) {
/* Create a slice */
numbers := []int{0.1.2.3.4.5.6.7.8}
printSlice(numbers)
/* Prints the original slice */
fmt.Println("numbers ==", numbers)
/* Print the subslice from index 1(included) to index 4(not included)*/
fmt.Println("numbers[1:4] ==", numbers[1:4])
/* The default lower limit is 0*/
fmt.Println("numbers[:3] ==", numbers[:3])
/* The default limit is len(s)*/
fmt.Println("numbers[4:] ==", numbers[4:])
numbers1 := make([]int.0.5)
printSlice(numbers1)
/* Print the subslice from index 0(included) to index 2(not included) */
number2 := numbers[:2]
printSlice(number2)
/* Print the subslice from index 2(included) to index 5(not included) */
number3 := numbers[2:5]
printSlice(number3)
}
func printSlice(x []int){
fmt.Printf("len=%d cap=%d slice=%v\n".len(x),cap(x),x)
}
Copy the code
The results
len=9 cap=9 slice=[0 1 2 3 4 5 6 7 8]
numbers == [0 1 2 3 4 5 6 7 8]
numbers[1:4] = = [1 2 3]
numbers[:3] = = [0 1 2]
numbers[4:] = = [4 5 6 7 8]
len=0 cap=5 slice=[]
len=2 cap=9 slice=[0 1]
len=3 cap=7 slice=[2 3 4]
Copy the code
Append () and copy() functions
Append appends one or more elements to slice and returns a slice copy function of the same type as Slice. Copy copies elements from the source slice SRC to the destination DST and returns the number of copied elements
The append function changes the contents of the array referenced by slice, affecting other slices that reference the same array. But when there is no remaining space in slice ((cap-len) == 0), new array space is allocated dynamically. The returned slice array pointer points to the space, while the contents of the original array remain unchanged; Other slices that reference this array are not affected
The following code describes the copy method for copying slices and the Append method for appending new elements to slices
package main
import "fmt"
func main(a) {
var numbers []int
printSlice(numbers)
/* Allow to append empty slices */
numbers = append(numbers, 0)
printSlice(numbers)
/* Adds an element */ to the slice
numbers = append(numbers, 1)
printSlice(numbers)
/* Add multiple elements */
numbers = append(numbers, 2.3.4)
printSlice(numbers)
/* Create slices numbers1 is double the size of previous slices */
numbers1 := make([]int.len(numbers), (cap(numbers))*2)
/* Copy the contents of numbers to numbers1 */
copy(numbers1,numbers)
printSlice(numbers1)
}
func printSlice(x []int){
fmt.Printf("len=%d cap=%d slice=%v\n".len(x),cap(x),x)
}
Copy the code
The results
len=0 cap=0 slice=[]
len=1 cap=1 slice=[0]
len=2 cap=2 slice=[0 1]
len=5 cap=6 slice=[0 1 2 3 4]
len=5 cap=12 slice=[0 1 2 3 4]
Copy the code
There is no connection between numbers and numbers1. When numbers change, numbers1 doesn’t change. That is, the copy method does not establish a link between two slices