[Go] Go language tutorial--Go language range (Range) (14)

Past review:

Article directory


The range keyword is a very common and easy-to-use syntactic sugar in the go language. It can be used in the for loop to iterate array, slice, map, channel, string and all things related to traversal output.

how to use?

We touched range for the first time in the loop in the previous section, and we also know that it can omit the key or the value to loop through, but this feature should be considered in combination with the actual situation.

The range keyword in the Go language is used to iterate the elements of an array (array), slice (slice), channel (channel) or collection (map) in a for loop. In arrays and slices it returns the index of the element and the value corresponding to the index, and in collections it returns a key-value pair.

The range format of the for loop can iterate over slices, maps, arrays, strings, etc. The format is as follows:

for key, value := range oldMap {
    
    
    newMap[key] = value
}

The key and value in the above code can be omitted.

If you only want to read the key, the format is as follows:

for key := range oldMap

or this:

for key, _ := range oldMap

If you only want to read the value, the format is as follows:

for _, value := range oldMap

Example
To traverse a simple array, the result of 2**%d is the corresponding power of 2:

example

package main

import "fmt"

var pow = []int{
    
    1, 2, 4, 8, 16, 32, 64, 128}

func main() {
    
    
   for i, v := range pow {
    
    
      fmt.Printf("2**%d = %d\n", i, v)
   }
}

The output of the above example run is:

2**0 = 1
2**1 = 2
2**2 = 4
2**3 = 8
2**4 = 16
2**5 = 32
2**6 = 64
2**7 = 128

The range format of the for loop can omit the key and value, as shown in the following example:

example

package main
import "fmt"

func main() {
    
    
    map1 := make(map[int]float32)
    map1[1] = 1.0
    map1[2] = 2.0
    map1[3] = 3.0
    map1[4] = 4.0
   
    // 读取 key 和 value
    for key, value := range map1 {
    
    
      fmt.Printf("key is: %d - value is: %f\n", key, value)
    }

    // 读取 key
    for key := range map1 {
    
    
      fmt.Printf("key is: %d\n", key)
    }

    // 读取 value
    for _, value := range map1 {
    
    
      fmt.Printf("value is: %f\n", value)
    }
}

The output of the above example run is:

key is: 4 - value is: 4.000000
key is: 1 - value is: 1.000000
key is: 2 - value is: 2.000000
key is: 3 - value is: 3.000000
key is: 1
key is: 2
key is: 3
key is: 4
value is: 1.000000
value is: 2.000000
value is: 3.000000
value is: 4.000000

range iterates over other data structures:

example

package main
import "fmt"
func main() {
    
    
    //这是我们使用 range 去求一个 slice 的和。使用数组跟这个很类似
    nums := []int{
    
    2, 3, 4}
    sum := 0
    for _, num := range nums {
    
    
        sum += num
    }
    fmt.Println("sum:", sum)
    //在数组上使用 range 将传入索引和值两个变量。上面那个例子我们不需要使用该元素的序号,所以我们使用空白符"_"省略了。有时侯我们确实需要知道它的索引。
    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)
    }
}

The output of the above example run is:

sum: 9
index: 1
a -> apple
b -> banana
0 103
1 111

Summarize

range can be used in for loop to iterate array, slice, map, channel, string and all things involved in traversing the output.
The implementation of for-range is actually a C-style for loop.
Using index and value to receive the return value of range will cause a data copy

Guess you like

Origin blog.csdn.net/u011397981/article/details/131740708