有没有办法操纵延迟堆栈? [英] Is there a way to manipulate the defer stack?
本文介绍了有没有办法操纵延迟堆栈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么办法可以改变延迟堆栈?例如,将调用添加到延迟堆栈的底部,还是删除最后放置的延迟?
Is there any way to change the defer stack? For example, adding a call to the bottom of the defer stack, or removing the last defer placed?
推荐答案
对 defer
堆栈的唯一可能修改是将其弹出".
The only modification possible to the defer
stack is to "pop" onto it.
话虽如此,您可以将defer设为可选,并使用一个变量从deferred函数中提早退出.示例:
Having said that, you could make a defer optional with a variable to early-exit from the deferred function. Example:
func foo() {
var skipDefer bool
defer func() {
if skipDefer {
return
}
// Do body of defer
}()
// Do stuff
if someConditionIsTrue {
skipDefer = true
}
defer func() {
// Do this one unconditionally
}
// Do other stuff
}
如果您确实想执行以下操作,也可以管理要手动执行的功能列表:
You could also manage a list of functions to be executed manually, if you really want to:
func foo() {
var deferreds []func()
defer func() {
for _, f := range deferreds {
f()
}
}()
// Add to and arrange `deferreds` to your heart's content
}
这篇关于有没有办法操纵延迟堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文