在 Go 中,我们使用 range
配合 for 循环来遍历数组、字符串或映射中的元素。
在学习 range
之前,请确保您了解 Golang for 循环 的工作原理。
Go for range 与数组
我们可以使用 for range
循环来访问数组的单个索引和元素。例如:
// Program using range with array
package main
import "fmt"
func main() {
// array of numbers
numbers := [5]int{21, 24, 27, 30, 33}
// use range to iterate over the elements of array
for index, item := range numbers {
fmt.Printf("numbers[%d] = %d \n", index, item)
}
}
输出
numbers[0] = 21 numbers[1] = 24 numbers[2] = 27 numbers[3] = 30 numbers[4] = 33
在上面的示例中,我们使用了 for range
for index, item := range numbers {
这里,range
关键字返回两个项:
- 数组索引:0、1、2,依此类推。
- 对应索引处的数组元素:21、24、27,依此类推。
要了解有关数组的更多信息,请访问 Golang 数组。
Golang 中 range 与字符串
在 Go 中,我们也可以使用 for range
关键字与字符串一起使用,以访问字符串的单个字符及其对应的索引。例如:
// Program using range with string
package main
import "fmt"
func main() {
string := "Golang"
fmt.Println("Index: Character")
// i access index of each character
// item access each character
for i, item := range string {
fmt.Printf("%d= %c \n", i, item)
}
}
输出
Index: Character 0: G 1: o 2: l 3: a 4: n 5: g
在上面的示例中,我们使用 for range
访问字符串 Golang 的单个字符及其对应的索引。
要了解有关字符串的更多信息,请访问 Golang 字符串。
for range 与 Go map
在 Go 中,我们也可以使用 for range
关键字与 map 一起使用来访问键值对。例如:
// Program using range with map
package main
import "fmt"
func main() {
// create a map
subjectMarks := map[string]float32{"Java": 80, "Python": 81, "Golang": 85}
fmt.Println("Marks obtained:")
// use for range to iterate through the key-value pair
for subject, marks := range subjectMarks {
fmt.Println(subject, ":", marks)
}
}
输出
Marks Obtained: Java: 80 Python: 81 Golang: 85
在每次迭代中,循环都会遍历 map 的键值对。
迭代 | 科目 | 分数 |
---|---|---|
1 | Java | 80 |
2 | Python | 81 |
3 | Golang | 85 |
要了解有关 map 的更多信息,请访问 Golang map。
使用 Go range 访问 Map 的键
我们也可以使用 for range
来仅访问 map 的键。例如:
// Program to retrieve the keys of a map
package main
import "fmt"
func main() {
// create a map
subjectMarks := map[string]float32{"Java": 80, "Python": 81, "Golang": 85}
fmt.Println("Subjects:")
for subject := range subjectMarks {
fmt.Println( subject)
}
}
输出
Subjects: Java Python Golang
在这里,我们使用了 range
来仅检索 map subjectMarks 的键 "Java"、"Python"、"Golang"。