range
關鍵字在for
迴圈中用於遍歷數組,切片,通道或映射的專案。 使用數組和切片,它返回項的索引為整數。 使用映射則它返回下一個鍵值對的鍵。 範圍返回一個或兩個值。如果在範圍運算式的左側僅使用一個值,則它是下表中的第一個值。
範圍運算式 | 第1個值 | 第2個值(可選) |
---|---|---|
數組或切片a[n]E | 索引 i 整數 | a[i]E |
Strubg s字串 | 索引 i 整數 | 符文整數 |
map m map[K]V | key k K | value m[k] V |
channel c chan E | element e E | none |
示例
以下是範圍應用的一些示例:
package main
import "fmt"
func main() {
/* create a slice */
numbers := []int{0,1,2,3,4,5,6,7,8}
/* print the numbers */
for i:= range numbers {
fmt.Println("Slice item",i,"is",numbers[i])
}
/* create a map*/
countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo"}
/* print map using keys*/
for country := range countryCapitalMap {
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}
/* print map using key-value*/
for country,capital := range countryCapitalMap {
fmt.Println("Capital of",country,"is",capital)
}
}
當上述代碼編譯和執行時,它產生以下結果:
Slice item 0 is 0
Slice item 1 is 1
Slice item 2 is 2
Slice item 3 is 3
Slice item 4 is 4
Slice item 5 is 5
Slice item 6 is 6
Slice item 7 is 7
Slice item 8 is 8
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo