33 lines
814 B
Go
33 lines
814 B
Go
|
package main
|
|||
|
|
|||
|
import "fmt"
|
|||
|
|
|||
|
func main() {
|
|||
|
data := []string{"one","two","three"}
|
|||
|
|
|||
|
// 非正确的捕获方式
|
|||
|
wrongFunctions := make([]func(), 0, 3)
|
|||
|
for _, v := range data {
|
|||
|
wrongFunctions = append(wrongFunctions, func() {
|
|||
|
fmt.Println(v)
|
|||
|
})
|
|||
|
}
|
|||
|
|
|||
|
for _, wrongFunc := range wrongFunctions {
|
|||
|
wrongFunc() // 输出 three three three,而不是期望的 one two three
|
|||
|
}
|
|||
|
|
|||
|
// 正确的捕获方式
|
|||
|
correctFunctions := make([]func(), 0, 3)
|
|||
|
for _, v := range data {
|
|||
|
value := v // 将值复制到了函数的每个局部版本
|
|||
|
correctFunctions = append(correctFunctions, func() {
|
|||
|
fmt.Println(value)
|
|||
|
})
|
|||
|
}
|
|||
|
|
|||
|
for _, correctFunc := range correctFunctions {
|
|||
|
correctFunc() // 输出 one two three
|
|||
|
}
|
|||
|
}
|