Learn the-go language pit for range

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.