PracticeDev/study_go/closer/main.go
2023-07-25 14:33:39 +08:00

33 lines
814 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
}
}