range _ golang
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 : .....
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。