Go Tutorial
Go Useful Resources
Selected Reading
- Go - 错误处理
- Go - Interfaces
- Go - 类型转换
- Go - 递归
- Go - Maps
- Go - 范围
- Go - 切片
- Go - 结构
- Go - 指针
- Go - 数组
- Go - 字符串
- Go - 作用域
- Go - 函数
- Go - 循环
- Go - 条件判断
- Go - 操作符
- Go - 常量
- Go - 变量
- Go - 数据类型
- Go - 基本语法
- Go - 程序结构
- Go - 环境设置
- Go - 概述
- Go - Home
Go Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Go - 范围
Go - 范围
range关键字在for循环中用于迭代数组、切片、通道或映射的项。对于数组和切片,它以整数形式返回项的索引。对于映射,它返回下一个键值对的键。范围返回一个值或两个值。如果在范围表达式的左侧仅使用一个值,则它是下表中的第一个值。
Range expression | 1st Value | 2nd Value(Optional) |
---|---|---|
Array or spce a [n]E | index i int | a[i] E |
String s string type | index i int | rune int |
map m map[K]V | key k K | value m[k] V |
channel c chan E | element e E | none |
Example
The following paragraph shows how to use range −
package main import "fmt" func main() { /* create a spce */ numbers := []int{0,1,2,3,4,5,6,7,8} /* print the numbers */ for i:= range numbers { fmt.Println("Spce 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) } }
When the above code is compiled and executed, it produces the following result −
Spce item 0 is 0 Spce item 1 is 1 Spce item 2 is 2 Spce item 3 is 3 Spce item 4 is 4 Spce item 5 is 5 Spce item 6 is 6 Spce item 7 is 7 Spce 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