add closer main
This commit is contained in:
parent
1f6df32092
commit
fdeef2f623
32
study_go/closer/main.go
Normal file
32
study_go/closer/main.go
Normal file
|
@ -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
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user