来源:https://github.com/xg-wang/gobyexample/tree/master/examples
package main
import "fmt"
func main() {
nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)
//`range`在数组和slice中提供对每项的索引和值的访问
for i, num := range nums {
if num == 3 {
fmt.Println("index:", i)
}
}
kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
fmt.Printf("%s -> %s\n", k, v)
}
//`range`也可以只遍历map的键
for k := range kvs {
fmt.Println("key:", k)
}
//`range`在字符串中迭代 unicode码点(code point)
//第一个返回值是字符的起始字节位置,然后第二个是字符本身
for i, c := range "go" {
fmt.Println(i, c)
}
}
输出结果:
sum: 9
index: 1
b -> banana
a -> apple
key: a
key: b
0 103
1 111