Pits encountered in function closures in Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Golang Project to use the Kafka, there is a component need to pull the cancellation of interest; The component starts up successfully, sometimes it pulls off the coupon, sometimes it feels like the card is dead, there is news, no one is pulled. Kafka test is not a problem; Finally, it is the problem of the function closure packet.

Looking at the code below, it looks like two goroutine, and we have rid as the goroutine marker, and the result should be:

1 abcdef012345601234561 abcdef1 abcdef......
 PackageMainImport("FMT"    "Sync"    "Time")funcMain () {strslice: = Make([]*string,0) S1: ="123456"Strslice =Append(Strslice, &s1) s2: ="ABCdef"Strslice =Append(Strslice, &S2)varWG Sync. Waitgroup forI,s: =Rangestrslice{WG. Add(1)Go func(rIdint){ for{FMT. Println (RId, *s) time. Sleep(1* Time. Second)} WG. Done ()} (i)} WG. Wait ()}

The result of the actual test is:

1 abcdef0 abcdef0 abcdef1 abcdef1 abcdef0 abcdef0 abcdef1 abcdef1 abcdef0 abcdef0 abcdef......

The s variable has been modified in the process of looping, so the result becomes this. Our project to get Kafka partition then each partition creates a goroutine to consume, so it only consumes the last partition of data, so there is a problem.

You can pass the same argument as the rid of an anonymous function, as in the following:

 for  I, s : = Range strslice{WG. ADD (1 ) go func (rId int , RS *string ) {for  {fmt. Println (rId, *rs ) time . Sleep (1  * time . Second)} WG. Done ()} (i, s )}  

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.