Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Go - "range variable i captured by func literal" #7

Open
huygn opened this issue Jun 4, 2016 · 0 comments
Open

Go - "range variable i captured by func literal" #7

huygn opened this issue Jun 4, 2016 · 0 comments
Labels

Comments

@huygn
Copy link
Owner

huygn commented Jun 4, 2016

When doing anonymous function inside a for loop, you might see a warning range variable i captured by func literal.

for i, e := range itemIDs {
    // This work as expected
    ii, ee := i, e
    go func() {
        defer wg.Done()
        if err := GetStoryByID(ee, &items[ii]); err != nil {
            log.Fatalf("Error: %s", err)
        }
    }()

    // This WONT work as expected
    go func() {
        defer wg.Done()
        if err := GetStoryByID(e, &items[i]); err != nil {
            log.Fatalf("Error: %s", err)
        }
    }()
}

With our go func().. statement we start a new goroutine. They run concurrently, which they do not run one after the other in an orderly fashion. They could in theory run one after the other, or they could all run at the same time (in parallel). Or maybe the "last one" runs first and then the "first one" and the "second one" runs last, or maybe.. think you get the point; it's unpredictable.

Ref: http://oyvindsk.com/writing/common-golang-mistakes-1

@huygn huygn added the golang label Jun 4, 2016
@huygn huygn changed the title Go - range variable i captured by func literal Go - "range variable i captured by func literal" Jun 6, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant