diff --git a/study_go/closer/main.go b/study_go/closer/main.go new file mode 100644 index 0000000..c210ac5 --- /dev/null +++ b/study_go/closer/main.go @@ -0,0 +1,32 @@ +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 + } +}