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