Learn the-go language pit for rangehttps://www.cnblogs.com/hetonghai/p/6718250.html
Go provides only a loop, a for loop, that can be used in the same way as C, or you can traverse container types such as arrays, slices, and mappings with a for range. However, when using a for range, if used improperly, there are some problems that cause the program to run less well than expected. For example, the following example program will traverse a slice and save the value of the slice as a mapped key and value, the slice type is an int, the type of the map is the key int, and the value is *int, that is, the value is an address.
package main import "fmt" func main() { slice := []int{0, 1, 2, 3} myMap := make(map[int]*int) for index, value := range slice { myMap[index] = &value } fmt.Println("=====new map=====") prtMap(myMap)} func prtMap(myMap map[int]*int) { for key, value := range myMap { fmt.Printf("map[%v]=%v\n", key, *value) }}
Run the program output as follows:
=====new map=====
Map[3]=3
Map[0]=3
Map[1]=3
Map[2]=3
The output can be known, not our expected output, the correct output should be as follows:
=====new map=====
Map[0]=0
Map[1]=1
map[2]=2
Map[3]=3
However, the output can tell that the values of the mappings are the same and are all 3. You can guess that the value of the map is the same address, traversing to the last element of the slice 3 o'clock, writes 3 to the address, so the mapping all values are the same. This is true because the for range creates a copy of each element instead of directly returning a reference to each element, and if the address of the value variable is used as a pointer to each element, it will result in an error, and in the iteration, the returned variable is a new variable that is assigned to the slice in turn during an iteration. So the address of the value is always the same, causing the result to be less than expected.
The following procedures are amended:
package main import "fmt" func main() { slice := []int{0, 1, 2, 3} myMap := make(map[int]*int) for index, value := range slice { num := value myMap[index] = &num } fmt.Println("=====new map=====") prtMap(myMap)} func prtMap(myMap map[int]*int) { for key, value := range myMap { fmt.Printf("map[%v]=%v\n", key, *value) }}
Run the program output as follows:
=====new map=====
map[2]=2
Map[3]=3
Map[0]=0
Map[1]=1
Egg-Fast execution is the key to success!
Go Language---for range