每次迭代独立的循环变量

版本新特性 / Go 1.22

tasks := []string{"a", "b", "c"}

// *** before: ***
for _, t := range tasks {
    go func() {
        fmt.Println(t) // t is one variable for the whole loop,
    }()                //  almost always prints "c", "c", "c"
}

// *** in version 1.22: ***
for _, t := range tasks {
    go func() {
        fmt.Println(t) // each iteration gets its own t
    }()                //  prints "a", "b", "c" in an arbitrary order
}