在Golang中,for-range结构用于遍历数组、切片、字符串、map 或者 结构体的字段。
- 遍历数组或切片:
package main
import "fmt"
func main() {
names := []string{"John", "Paul", "George", "Ringo"}
for index, value := range names {
fmt.Printf("Index: %d, Value: %s\n", index, value)
}
}
- 遍历字符串:
package main
import "fmt"
func main() {
str := "Hello, World!"
for index, value := range str {
fmt.Printf("Index: %d, Value: %c\n", index, value)
}
}
- 遍历map:
package main
import "fmt"
func main() {
person := map[string]int{"John": 30, "Peter": 25, "Alice": 22}
for key, value := range person {
fmt.Printf("Key: %s, Value: %d\n", key, value)
}
}
- 遍历结构体:
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p := Person{"John", 30}
for i, v := range p {
fmt.Printf("Field %d: %v\n", i, v)
}
}
注意:for-range结构不支持并发遍历,如果需要在遍历过程中修改被遍历的对象,可以使用传统的for循环。