Go Language Chapter 4 (Arrays and Slices)

Go Language Chapter 4 (Arrays and Slices)

First of all, if you don't have a compiler, you can type code through this URL: Lightly

Introduction

In the Go language, an array is a fixed-length data structure used to store a set of elements of the same type. The length of the array is determined when it is created and cannot be changed.

array

Array declaration and initialization

In Go language, you can use the var keyword and the array type to declare an array, and then use {} to initialize the value of the array. For example:

var arr [5]int
arr = [5]int{
    
    1, 2, 3, 4, 5}

The above code defines an integer array of length 5 and initializes it to {1, 2, 3, 4, 5}.

Arrays can also be declared and initialized in the following simplified way:

arr := [5]int{
    
    1, 2, 3, 4, 5}

This code example has the same effect as the previous code example, but uses the short variable declaration syntax to declare and initialize the array.

If you want the compiler to automatically calculate the length of the array, you can use ... instead of the specific length value, for example:

arr := [...]int{
    
    1, 2, 3, 4, 5}

The above code will automatically calculate the length of the array as 5.

Array access and traversal

In the Go language, you can use subscripts to access elements in an array. The subscript of the array starts from 0 and increases one by one, the maximum value is the length of the array minus 1. For example:

arr := [5]int{
    
    1, 2, 3, 4, 5}
fmt.Println(arr[0]) // 输出 1
fmt.Println(arr[4]) // 输出 5

You can use a for loop to iterate over all elements in an array. For example:

arr := [5]int{
    
    1, 2, 3, 4, 5}
for i := 0; i < len(arr); i++ {
    
    
    fmt.Println(arr[i])
}

You can also use the range keyword to traverse the array, and the range expression returns the index and corresponding value of the array. For example:

arr := [5]int{
    
    1, 2, 3, 4, 5}
for index, value := range arr {
    
    
    fmt.Printf("索引:%d,值:%d\n", index, value)
}

The above is the basic usage of arrays in Go language. It should be noted that when writing code, ensure that the subscript does not cross the boundary, and pay attention to the matching of the array length and data type.

example

1. Calculate and output the sum of all elements in the given array

package main

import "fmt"

func main() {
    
    
    arr := [5]int{
    
    1, 2, 3, 4, 5}
    sum := 0
    for i := 0; i < len(arr); i++ {
    
    
        sum += arr[i]
    }
    fmt.Printf("数组 %v 的元素之和为 %d\n", arr, sum)
}

operation result:
insert image description here

2. Find the specified element in the given array and output the subscript of the element

package main

import "fmt"

func main() {
    
    
    arr := [5]int{
    
    1, 2, 3, 4, 5}
    target := 3
    index := -1
    for i := 0; i < len(arr); i++ {
    
    
        if arr[i] == target {
    
    
            index = i
            break
        }
    }
    if index >= 0 {
    
    
        fmt.Printf("元素 %d 在数组 %v 中的下标为 %d\n", target, arr, index)
    } else {
    
    
        fmt.Printf("元素 %d 不在数组 %v 中\n", target, arr)
    }
}

operation result:
insert image description here

3. Arrange the elements in the given array in reverse order and output the result

package main

import "fmt"

func main() {
    
    
    arr := [5]int{
    
    1, 2, 3, 4, 5}
    for i := 0; i < len(arr)/2; i++ {
    
    
        j := len(arr) - i - 1
        arr[i], arr[j] = arr[j], arr[i]
    }
    fmt.Println("数组倒序后为:", arr)
}

operation result:
insert image description here

slice

Introduction

A slice is a dynamic-length data structure that can automatically grow or shrink as needed. In Go language, you can use to []Trepresent a slice whose element type is T, and use makethe function to create an empty slice with a specified length and capacity. For example:

var slice []int
slice = make([]int, 5)

The above code defines an integer slice with length and capacity of 5. If only length is specified without capacity, the capacity of the slice is the same as the length. You can use subscripts to access elements in a slice, for example:

fmt.Println(slice[0]) // 输出 0
fmt.Println(slice[4]) // 输出 0

At the same time, you can also use the for loop or the range keyword to traverse all elements in the slice.

It should be noted that if you assign some elements of an array to a slice, the slice will refer to some elements of the original array. If you modify an element in the slice, the corresponding element in the original array will also be modified. For example:

arr := [5]int{
    
    1, 2, 3, 4, 5}
slice := arr[1:4]
slice[0] = 10
fmt.Println(arr)   // 输出 [1 10 3 4 5]
fmt.Println(slice) // 输出 [10 3 4]

The above is the basic concept of array and slice in Go language. It should be noted that when using arrays and slices, ensure that the subscript does not cross the boundary, and pay attention to the matching of the array length and data type.

example

1. Write a function that calculates the average of all elements in a given integer array.

package main

import "fmt"

func average(arr [5]int) float64 {
    
    
    sum := 0
    for i := 0; i < len(arr); i++ {
    
    
        sum += arr[i]
    }
    return float64(sum) / float64(len(arr))
}

func main() {
    
    
    arr := [5]int{
    
    1, 2, 3, 4, 5}
    fmt.Printf("数组 %v 的平均值为 %.2f\n", arr, average(arr))
}

operation result:
insert image description here

2. Write a function that adds all elements in a given integer slice and returns the result.

package main

import "fmt"

func sum(slice []int) int {
    
    
    result := 0
    for i := 0; i < len(slice); i++ {
    
    
        result += slice[i]
    }
    return result
}

func main() {
    
    
    slice := []int{
    
    1, 2, 3, 4, 5}
    fmt.Printf("切片 %v 中所有元素的和为 %d\n", slice, sum(slice))
}

operation result:
insert image description here

3. Write a function that replaces all odd elements in a given integer slice with their squared values ​​and outputs the modified result.

package main

import "fmt"

func squareOdd(slice []int) {
    
    
    for i := 0; i < len(slice); i++ {
    
    
        if slice[i]%2 == 1 {
    
    
            slice[i] *= slice[i]
        }
    }
}

func main() {
    
    
    slice := []int{
    
    1, 2, 3, 4, 5}
    fmt.Println("修改前:", slice)
    squareOdd(slice)
    fmt.Println("修改后:", slice)
}

operation result:
insert image description here

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/130108712