range iterates over of elements in variety of data structures. Let's see how use range with some of the data structures we've already leraned
package main import ( "fmt" ) func main() { nums := []int{1, 2, 3} sum := 0 for a, num := range nums { sum += num fmt.Println("a:", a) } fmt.Println("sum :", sum) 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) } for i, c := range "go" { fmt.Println(i, c) } }
a: 0 a: 1 a: 2 sum : 6 index: 2 b -> banana a -> apple 0 103 1 111
总结
1 : .....
有疑问加站长微信联系(非本文作者)