Go language pit for range

Source: Internet
Author: User

Programming always encounter a variety of strange strange pits, the correct mastery of language use posture, can effectively avoid stepping on the pit flashing waist.

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.

Situation. One

> for range + 闭包The code is as follows: ( closure related can see my previous blog )

package mainimport (    "fmt"    "time")func main()  {    str := []string{"I","am","Sergey"}    forrange str{        gofunc() {            fmt.Println(v)        }()    }    time.Sleep(3 * time.Second)}----------输出结果:SergeySergeySergey

The intent of the program is to traverse the string slices and print them out, but the output only outputs the last element of the slice.

The reason for this is that a reference to a value that is not passed in as a parameter in a closure is quoted as passing ... In other words, it refers to the println(v) address of V and then dereference it to print the value. When this goroutine executes println(v) , the value pointed to by V is already "Sergey"

If you want to print correctly, define a parameter when defining the closure and pass V as a parameter. The following code is modified:

package mainimport (    "fmt"    "time")func main()  {    str := []string{"I","am","Sergey"}    forrange str{        gofuncstring) {            fmt.Println(v)        }(v)    }    time.Sleep(3 * time.Second)}

In addition, the output is not necessarily I am Sergey, because the goroutine execution sequence is determined by the Go Runtime scheduler

Situation. Two

> 操作map,原理和情形一类似The code is as follows:

 PackageMainImport "FMT"funcMain () {slice: = []int{0,1,2,3} MYMAP: = Make(Map[int]*int) forIndex, Value: =RangeSlice {Mymap[index] = &value} prtmap (MYMAP)}funcPrtmap (MyMapMap[int]*int) { forKey, Value: =RangeMyMap {fmt. Printf ("map[%v]=%v\n", Key, *value)}}----------output:Map[0]=3Map[1]=3Map[2]=3Map[3]=3

Explanation of Reason: But 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.

Make a little change to get the results we expect:

 PackageMainImport "FMT"funcMain () {slice: = []int{0,1,2,3} MYMAP: = Make(Map[int]*int) forIndex, Value: =RangeSlice {V: = value mymap[index] = &v} prtmap (MYMAP)}funcPrtmap (MyMapMap[int]*int) { forKey, Value: =RangeMyMap {fmt. Printf ("map[%v]=%v\n", Key, *value)}}
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.