Go 迭代切片

迭代切片有两种方式:
1. 使用 for range 迭代切片
 
// 其长度和容量都是 4 个元素
slice := []int{10, 20, 30, 40}
// 迭代每一个元素,并显示其值
for index, value := range slice {
fmt.Printf("Index: %d Value: %d
", index, value)
} 
Output:
Index: 0 Value: 10
Index: 1 Value: 20
Index: 2 Value: 30
Index: 3 Value: 40

2.使用传统的 for 循环对切片进行迭代

// 其长度和容量都是 4 个元素
slice := []int{10, 20, 30, 40}
// 从第三个元素开始迭代每个元素
for index := 2; index < len(slice); index++ {
fmt.Printf("Index: %d Value: %d
", index, slice[index])
} 
Output:
Index: 2 Value: 30
Index: 3 Value: 40
 
原文地址:https://www.cnblogs.com/guangzhou11/p/10868428.html