切片的遍历和数组的遍历非常类似,可以使用for循环索引遍历,或者for range循环。
for循环索引遍历
package main
import "fmt"
func main() {
s1 := []int{1, 2, 3, 4, 5}
for i := 0; i < len(s1); i++ {
fmt.Printf("s1[%d]: %v\n", i, s1[i])
}
}
运行结果
[Running] go run "/Users/guoliang/SynologyDrive/软件开发/go/golang入门到项目实战/goproject/360duote.com/pro01/test.go"
s1[0]: 1
s1[1]: 2
s1[2]: 3
s1[3]: 4
s1[4]: 5
for range循环
package main
import "fmt"
func main() {
s1 := []int{1, 2, 3, 4, 5}
for i, v := range s1 {
fmt.Printf("s1[%d]: %v\n", i, v)
}
}
运行结果
[Running] go run "/Users/guoliang/SynologyDrive/软件开发/go/golang入门到项目实战/goproject/360duote.com/pro01/test.go"
s1[0]: 1
s1[1]: 2
s1[2]: 3
s1[3]: 4
s1[4]: 5