Go language range keyword loop when the pit

  • 2020-06-19 10:32:21
  • OfStack

The keyword range Can be used for loops, similar to iterator operations, which can be traversed slice , array , string , map and channel , and then returns the index or value. You can use "_" to ignore unwanted return values. You can easily read the content in the above type, for example:


package main
import "fmt"
func main() {
  str1 := []string{"1", "2", "3", "4"}
  for key, value := range str1 {
    fmt.Println(key, ":", value)
  }
}

But if you want to change these types of values, using range may not work as well as you'd like. For example, change the values "2" and "4" in str1 above to "6" and use range for traversal modifications.


package main
import "fmt"
func main() {
  str1 := []string{"1", "2", "3", "4"}
  for _, value := range str1 {
    if value == "2" || value == "4" {
      value = "6"
    }
  }
  fmt.Println(str1)
}

You might think it would be [1 6 3 6] But the implementation is [1 2 3 4] . That is to say, the operation of the section in range did not affect the section (original section).

[

The reason for the above problem is that for range The traversal content is a copy of the original content, so it cannot be used to modify the content in the original slice.

]

Modification method:

[

Use the for statement

]

package main
import "fmt"
func main() {
  str1 := []string{"1", "2", "3", "4"}
  for i := 0; i < len(str1); i++ {
    if str1[i] == "2" || str1[i] == "4" {
      str1[i] = "6"
    }
  }
  fmt.Println(str1)
}

conclusion


Related articles: