PracticeDev/study_go/closer/main.go

33 lines
814 B
Go
Raw Permalink Normal View History

2023-07-25 14:33:39 +08:00
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
}
}