Golang 如何使用for循环遍历数组

Golang 如何使用for循环遍历数组

数组是存储在连续空间中类似类型项的集合的数据结构。在对数组执行操作时,需要遍历它。编程语言中使用 for循环 遍历数据结构,可以在以下方式中使用:

示例1:

// Golang program to iterate over
      // an Array using for loop
      package main

      import "fmt"

      func main() {

        // taking an array
        arr := [5]int{1, 2, 3, 4, 5}
        fmt.Println("The elements of the array are: ")

        // using for loop
        for i := 0; i < len(arr); i++ {
          fmt.Println(arr[i])
        }
      } 

输出:

The elements of the array are:
1
2
3
4
5

说明: 变量i初始化为0,并定义为在每次迭代中增加,直到达到数组长度的值。然后,给出打印命令,以逐个打印数组每个索引处的元素。

示例2: for循环可以使用另一个关键字 return 来执行迭代。

// Golang program to iterate over
      // an Array using for loop
      package main

      import "fmt"

      func main() {

        // taking an array
        arr := [5]string{"Ronaldo", "Messi", "Kaka", "James", "Casillas"}
        fmt.Println("The elements of the array are:")

        // using for loop
        for index, element := range arr {
          fmt.Println("At index", index, "value is", element)
        }
      } 

输出:

The elements of the array are:
At index 0 value is Ronaldo
At index 1 value is Messi
At index 2 value is Kaka
At index 3 value is James
At index 4 value is Casillas

说明: 关键字 range 将迭代范围设置为数组的长度。变量index和element分别存储数组的索引和值。

示例3: 如果不需要索引,可以使用下划线 _ 来忽略它。

// Golang program to iterate over
      // an Array using for loop
      package main

      import "fmt"

      func main() {

        // taking an array
        arr := []int{1, 2, 3, 4, 5}
        fmt.Println("The elements of the array are:")

        // using for loop
        for _, value := range arr {
          fmt.Println(value)
        }
      } 

输出:

The elements of the array are:
1
2
3
4
5

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程