f*******t 发帖数: 7549 | 1 package main
import (
"fmt"
)
func compute(addSample func(int)) {
addSample(1)
addSample(2)
}
func main() {
var samples []int
addSample := func(n int) {
samples = append(samples, n)
}
defer fmt.Println(len(samples), "samples are added. expecting 2")
compute(addSample)
}
实际输出是
0 samples are added. expecting 2
文档解释:
A deferred function's arguments are evaluated when the defer statement is
evaluated.
所以千万别把defer当closure用,否则有可能出难以解释的bug |
W********u 发帖数: 58 | 2 这只能说明你看文档太不仔细了,这说得很清楚啊,还有例子呢:
http://blog.golang.org/defer-panic-and-recover
1. A deferred function's arguments are evaluated when the defer statement is
evaluated.
In this example, the expression "i" is evaluated when the Println call is
deferred. The deferred call will print "0" after the function returns.
func a() {
i := 0
defer fmt.Println(i)
i++
return
} |
d****n 发帖数: 1637 | 3 function closure
【在 f*******t 的大作中提到】 : package main : import ( : "fmt" : ) : func compute(addSample func(int)) { : addSample(1) : addSample(2) : } : func main() { : var samples []int
|