如何实现像python中go的defer
语句这样的工作呢?
Defer将函数调用推送到堆栈。当包含defer语句的函数返回时,将在defer语句最初所在的范围内逐个弹出并执行延迟的函数调用。Defer语句看起来像函数调用,但在弹出之前不会执行。
举例说明它的工作原理:
func main() {
fmt.Println("counting")
var a *int
for i := 0; i < 10; i++ {
a = &i
defer fmt.Println(*a, i)
}
x := 42
a = &x
fmt.Println("done")
}
输出:
counting
done
9 9
8 8
7 7
6 6
5 5
4 4
3 3
2 2
1 1
0 0
用例示例:
var m sync.Mutex
func someFunction() {
m.Lock()
defer m.Unlock()
// Whatever you want, with as many return statements as you want, wherever.
// Simply forget that you ever locked a mutex, or that you have to remember to release it again.
}
Python的with statement与Go的defer有类似的用途。
Python中类似的代码是:
我做了一个there(与2.x兼容):
defers_collector
的来源是:要模拟} :
defer fmt.Println(*a, i)
示例,可以use ^{Output
很容易模拟互斥情况:
相关问题 更多 >
编程相关推荐