Skip to content

Incorrect use of closures in Effective Go documentation #6502

@gopherbot

Description

@gopherbot

by shiblon:

In the Effective Go document, the following example appears in the Goroutines section:

func Serve(queue chan *Request) {
    for req := range queue {
        <-sem
        go func() {
            process(req)
            sem <- 1
        }()
    }
}

This example is not going to work, however, because "req" gets reused at every
iteration of the loop. In order for it to be correct, it would either need "req :=
req" at the beginning of the loop body, or the request should be passed in thus:

func Serve(queue chan *Request) {
    for req := range queue {
        <-sem
        go func(r *Request) {
            process(r)
            sem <- 1
        }(req)
    }
}

I am not sure which of the two approaches would be more idiomatic in Go (creating a new
local variable at every iteration vs. passing in a parameter), but the one that is
currently there appears incorrect.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions