阅读量:1
在 Go 语言中,遍历切片(slice)的方法有很多种。这里为您提供三种常用的遍历方法:
- 使用 for 循环遍历:
package main
import "fmt"
func main() {
slice := []int{1, 2, 3, 4, 5}
for index := 0; index < len(slice); index++ {
fmt.Printf("Index: %d, Value: %d\n", index, slice[index])
}
}
- 使用 range 关键字遍历:
package main
import "fmt"
func main() {
slice := []int{1, 2, 3, 4, 5}
for index, value := range slice {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
}
- 使用 for i := 0; i < len(slice); i++ 遍历(与第一种方法类似):
package main
import "fmt"
func main() {
slice := []int{1, 2, 3, 4, 5}
for i := 0; i < len(slice); i++ {
fmt.Printf("Index: %d, Value: %d\n", i, slice[i])
}
}
以上三种方法都可以用于遍历 Go 语言的切片。其中,第二种方法(使用 range 关键字)是最简洁的,因为它可以直接获取到切片的索引和值,而不需要手动管理索引变量。
以上就是关于“怎样遍历go语言切片”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm