for
循环可用于遍历数组中的元素。
package main
import "fmt"
func main() {
a := [...]float64{67.7, 89.8, 21, 78}
for i := 0; i < len(a); i++ { //从0循环到数组的长度
fmt.Printf("%d th element of a is %.2f\n", i, a[i])
}
}
上面的程序使用for
循环遍历数组元素,从索引0
到数组长度 - 1
。
这个程序将打印,
0 th element of a is 67.70
1 th element of a is 89.80
2 th element of a is 21.00
3 th element of a is 78.00
range
Go通过使用for
循环的range
形式,提供了一种更好更简洁的遍历数组方法。range
同时返回索引和该索引处的值。
让我们使用range重写上面的代码。我们还将计算数组中所有元素的和。
package main
import "fmt"
func main() {
a := [...]float64{67.7, 89.8, 21, 78}
sum := float64(0)
for i, v := range a {//range同时返回索引和值
fmt.Printf("%d the element of a is %.2f\n", i, v)
sum += v
}
fmt.Println("\nsum of all elements of a",sum)
}
上面的程序中,for i, v := range a
是for
循环的range
形式,它将同时返回索引和该索引处的值。
程序将输出:
0 the element of a is 67.70
1 the element of a is 89.80
2 the element of a is 21.00
3 the element of a is 78.00
sum of all elements of a 256.5
如果只想要值,不想要索引,可以通过用_
blank标识符替换索引来实现。
for _, v := range a { //忽略索引
上面的for
循环忽略了索引。类似地,值也可以忽略。