This is a creation in Article, where the information may have evolved or changed.
First, usage
Range is similar to iterators, which can traverse arrays, strings, maps, and so on, and return different results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
Package main import "FMT" func main(){ //Array traversal A: = [3]int {1, 2, 3} for i, N: = range a{ FMT. Println (i, N) } //Slice traversal B: = []int{2, 3, 4} for i, N: = range b{ FMT. Println (i, N) } traversal of the//map c: = map[string]int{"Hello":1, "World": 2} for k, V: = range c{ FMT. Println (k, v) } }
|
Results:
1 2 3 4 5 6 7 8
|
0 1 1 2 2 3 0 2 1 3 2 4 Hello 1 World 2
|
Second, the matters needing attention
1. Range copies the object instead of manipulating it directly on the original object.
Example one:
1 2 3 4 5 6 7 8 9 |
package main import func main () { a: = [3 ]int {1 , 2 , 3 } for _, V: = range a {//copy a Traversal [1, 2, 3] V + = 100 //v is a value in the copied object and does not change the value of the A array element /span> FMT. Println (a) //1 2 3 } |
Example two:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
Package main import "FMT" func main(){ A: = [3]int {1, 2, 3} for i, V: = range a{ //i,v extracted from a copied object if i = = 0{ a[1], a[2] = FMT. Println (a) //Output [1] } A[i] = v + //v is the element in the copied object [1, 2, 3] } FMT. Println (a) //Output [101, 102, 103] }
|
2. When iterating through reference types using range iterations, the underlying data is not copied:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
Package main import "FMT" func main(){ A: = []int {1, 2, 3} //change to slice for i, V: = range a{ if i = = 0{ a[1], a[2] = FMT. Println (a) //[1 } A[i] = v + } FMT. Println (a) }
|
Results:
Because the internal structure of the slice is struct slice{*point, Len, Cap}.
The data section is a pointer to the address, copying the object only when the value of the pointer is copied, instead of re-copying a new piece of memory and then put the value in, so the change is still modified when the original value, and C + + in the same light copy.