range是Go中用于遍历集合的for循环语法,可遍历数组、切片、字符串、map和channel;它返回索引和元素副本,支持只取其一或两者都取,常用于简洁高效地迭代数据结构。

在Golang中,range 是 for 循环的一种特殊形式,用于遍历数组、切片、字符串、map 和 channel。使用 range 遍历数组和切片非常常见,语法简洁且高效。
你可以选择接收其中一个或两个值:
fruits := []string{"apple", "banana", "cherry"}
for i, fruit := range fruits {
fmt.Printf("索引 %d: %s\n", i, fruit)
}
索引 0: apple
索引 1: banana
索引 2: cherry
for _, fruit := range fruits {
fmt.Println(fruit)
}
for i := range fruits {
fmt.Println("位置:", i)
}
numbers := [3]int{10, 20, 30}
for i, num := range numbers {
fmt.Printf("第%d项是%d\n", i, num)
}
以上就是如何在Golang中使用range遍历数组和切片的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号