📜  Golang 中的 Range 关键字

📅  最后修改于: 2021-10-25 02:13:46             🧑  作者: Mango

在 Golang 中Range关键字用于不同类型的数据结构中以迭代元素。 range关键字主要用于 for 循环,以便迭代mapslicechannel数组的所有元素。当它遍历数组的元素并切片时,它会以整数形式返回元素的索引。当它遍历映射的元素时,它会返回后续键值对的键。此外,范围可以返回一个值或两个值。让我们看看在 Golang 中迭代不同类型的集合时返回什么范围

  • 数组或切片:数组或切片返回的第一个值是index ,第二个值是element
  • 字符串:字符串返回的第一个值是index ,第二个值是rune int
  • 图:图返回的第一个值是密钥和所述第二值是在图中的键-值对的
  • 通道:通道中返回的第一个值是element ,第二个值是none

现在,让我们看一些例子来说明范围关键字在 Golang 中的用法。

示例 1:

// Golang Program to illustrate the usage
// of range keyword over items of an
// array in Golang
 
package main
 
import "fmt"
 
// main function
func main() {
 
    // Array of odd numbers
    odd := [7]int{1, 3, 5, 7, 9, 11, 13}
 
    // using range keyword with for loop to
    // iterate over the array elements
    for i, item := range odd {
 
        // Prints index and the elements
        fmt.Printf("odd[%d] = %d \n", i, item)
    }
}

输出:

odd[0] = 1
odd[1] = 3
odd[2] = 5
odd[3] = 7
odd[4] = 9
odd[5] = 11
odd[6] = 13

在这里,所有元素都打印有各自的索引。

示例 2:

// Golang Program to illustrate the usage of
// range keyword over string in Golang
 
package main
 
import "fmt"
 
// Constructing main function
func main() {
 
    // taking a string
    var string = "GeeksforGeeks"
 
    // using range keyword with for loop to
    // iterate over the string
    for i, item := range string {
 
        // Prints index of all the
        // characters in the string
        fmt.Printf("string[%d] = %d \n", i, item)
    }
}

输出:

string[0] = 71 
string[1] = 101 
string[2] = 101 
string[3] = 107 
string[4] = 115 
string[5] = 102 
string[6] = 111 
string[7] = 114 
string[8] = 71 
string[9] = 101 
string[10] = 101 
string[11] = 107 
string[12] = 115

在这里,打印的项目是rune ,即构成字符串的所述字符的int32 ASCII 值。

示例 3:

// Golang Program to illustrate the usage of
// range keyword over maps in Golang
 
package main
 
import "fmt"
 
// main function
func main() {
 
    // Creating map of student ranks
    student_rank_map := map[string]int{"Nidhi": 3,
                           "Nisha": 2, "Rohit": 1}
 
    // Printing map using keys only
    for student := range student_rank_map {
        fmt.Println("Rank of", student, "is: ",
                     student_rank_map[student])
    }
 
    // Printing maps using key-value pair
    for student, rank := range student_rank_map {
        fmt.Println("Rank of", student, "is: ", rank)
    }
}

输出:

Rank of Nidhi is:  3
Rank of Nisha is:  2
Rank of Rohit is:  1
Rank of Nidhi is:  3
Rank of Nisha is:  2
Rank of Rohit is:  1

因此,这里首先仅使用键打印输出,然后再次使用键和值打印输出。