-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap_range.go
More file actions
49 lines (41 loc) · 1.42 KB
/
map_range.go
File metadata and controls
49 lines (41 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main
import "fmt"
func main() {
var countryMap map[string]string
countryMap = make(map[string]string)
countryMap["France"] = "Paris"
countryMap["Italy"] = "Rome"
countryMap["Japan"] = "Tokyo"
countryMap["India"] = "New Delhi"
for country := range countryMap{
fmt.Println("Capital of ", country, "is ", countryMap[country])
}
capital, ok := countryMap["USA"]
if(ok){
fmt.Println("Capital of United States is", capital)
}else {
fmt.Println("Capital of United States is not present")
}
//这是我们使用range去求一个slice的和。使用数组跟这个很类似
nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)
//在数组上使用range将传入index和值两个变量。上面那个例子我们不需要使用该元素的序号,所以我们使用空白符"_"省略了。有时侯我们确实需要知道它的索引。
for i, num := range nums {
if num == 3 {
fmt.Println("index:", i)
}
}
//range也可以用在map的键值对上。
kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
fmt.Printf("%s -> %s\n", k, v)
}
//range也可以用来枚举Unicode字符串。第一个参数是字符的索引,第二个是字符(Unicode的值)本身。
for i, c := range "go" {
fmt.Println(i, c)
}
}