Home >Common Problem >How to use arrays in golang

How to use arrays in golang

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2023-06-09 11:10:17916browse

The way golang uses arrays is: 1. Define and initialize the array, the syntax is "var a [5]int"; 2. Access the array elements, the syntax is "x := a[1]" ; 3. Traverse the array and use the for loop structure; 4. Pass the array as a function parameter, but it will not affect the original array.

How to use arrays in golang

Operating system for this tutorial: Windows 10 system, Go1.20.1 version, Dell G3 computer.

Array in Golang is a data structure with fixed length and the same element type. You can use subscript index to access the elements in the array.

The following are common usages and sample codes for using arrays:

1. Definition and initialization of arrays

var a [5]int // 声明一个长度为5的int类型的数组
b := [3]string{"apple", "banana", "orange"} // 声明一个长度为3的string类型的数组并进行初始化
c := [...]float64{1.2, 3.4, 5.6} // 声明一个根据初始化值自动推导长度的float64类型的数组

2. Accessing arrays Element

a[0] = 1 // 通过下标赋值
x := a[1] // 通过下标获取值

3. Traversing the array

for i := 0; i < len(a); i++ {
    fmt.Println(a[i])
}
for index, value := range b {
    fmt.Printf("%d: %s\n", index, value)
}

4. Array as function parameter

func printArray(arr [3]int) {
    for _, v := range arr {
        fmt.Print(v)
    }
}
func main() {
    d := [3]int{1, 2, 3}
    printArray(d) // 输出结果为123
}

Things to note Yes, in Go language, an array will be copied when passed as a function parameter, so modifying the array in the function body will not affect the original array. If you need to modify the array in place, you can use slicing.

The above is the detailed content of How to use arrays in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn