# range _ golang

jackkiexu · · 1825 次点击 · · 开始浏览

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

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

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