go语言内置一个关键字range用于迭代集合,当然他也可以迭代slice,也可以使用 _ 来忽略我们不关心的元素,但是如果只关心index则不需这么写 for index,_ := range slice1。下在给出完整代码
package main
import (
"fmt"
)
func main() {
// 创建一个容量和长度均为6的slice
slice1 := []int{5, 23, 10, 2, 61, 33}
for index, value := range slice1 {
fmt.Println("index:", index, "value:", value)
}
// 可以忽略我们不关心的元素
// 只关心value
for _, value := range slice1 {
fmt.Println("value:", value)
}
// 只关心index, 可以不用 _
for index := range slice1 {
fmt.Println("index:", index)
}
}
"C:\Program Files\JetBrains\Gogland 172.3757.46\bin\runnerw.exe" D:/Go\bin\go.exe run D:/Go/code/src/awesomeProject/reflect.go
index: 0 value: 5
index: 1 value: 23
index: 2 value: 10
index: 3 value: 2
index: 4 value: 61
index: 5 value: 33
value: 5
value: 23
value: 10
value: 2
value: 61
value: 33
index: 0
index: 1
index: 2
index: 3
index: 4
index: 5
Process finished with exit code 0