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 )}