golang不寻常的Go构造:创建可重用的名称:name:= name…Somethiing [关闭]

I saw this construct somewhere for reusing a "name" when sending data to a function.

I am working with a database and need to send a lot of "named" buffers to be processed. This construct seems perfect, but I can not make work and can not remember where I saw it discussed.

Any Help would be appreciated.

The jist of the text was that each time you used this contruct the name would be used over and over, but each instance would be actually own it's own for collection.

all I remember is that it was name := name ..then something. I am Lost here.

Did you mean a construct like this:

func foo() {
    var bar // some variable

    go func() {
        bar := bar // copy bar into inner scope
    }()
}

You're definitely referring to creating copies of loop variables. Normally, in this code:

for i := 0; i < 100; i++ {
    go func() {
        fmt.Println(i)
    }
}

i will reference the loop variable in all goroutines, so if the goroutines spawn and then the loop keeps going before they call fmt.Println(i), i will be a different value when they call it than when they were spawned from the loop. One way around this is to do, as you mentioned:

for i := 0; i < 100; i++ {
    i := i
    go func() {
        fmt.Println(i)
    }
}

The added line, i := i, introduces a local variable called i, and sets it equal to the loop variable i. These are two distinct variables. You might as well say j := i and then use j instead. I tend to think that using i := i is more confusing, but some people prefer it. In any case, given that it's a local variable, there's a different instance of it per loop, which means that each goroutine sees its own unique instance that won't be changed.

While this idiom can be found in Effective Go (search for "req := req" on the page), let me be clear about something: this is confusing and should be avoided. I don't know why the Go authors thought it was a good idea to introduce this idiom, and, in my opinion, it should be avoided. Why? Because there's a much cleaner way to accomplish the same thing that is much more understandable:

for i := 0; i < 100; i++ {
    go func(i int) {
        fmt.Println(i)
    }(i)
}

In this version, the anonymous function takes a single integer argument, and when it is spawned in a goroutine, the loop variable i is passed as that argument. People have a much more solid understanding of these semantics, and so it's much easier to see what this does and understand why it works. If this is still confusing, I suggest changing the argument name:

for i := 0; i < 100; i++ {
    go func(j int) {
        fmt.Println(j)
    }(i)
}

I think these two approaches are much more understandable and should be used instead of the example you mentioned.