Reference from http://studygolang.com/articles/9701
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 Mainimport "FMT" Func Main () { slice: = []int{0, 1, 2, 3} MyMap: = Do (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]=3map[0]=3map[1]=3map[2]=3
The output can be known, not our expected output, the correct output should be as follows:
=====new map=====map[0]=0map[1]=1map[2]=2map[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 causes an error , at the time of 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 , resulting in less than expected results.
The following procedures are amended:
Package Mainimport "FMT" Func Main () { slice: = []int{0, 1, 2, 3} MyMap: = Do (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]=2map[3]=3map[0]=0map[1]=1
Learn the-go language pit for range