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 : .....

posted on 2015-03-13 15:00  xjk112  阅读(168)  评论(0编辑  收藏  举报