如何实现类似于deferPython 中 go 语句的功能?
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
Go 用例示例:
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.
}
一只甜甜圈
饮歌长啸
杨魅力
相关分类