有没有办法操纵延迟堆栈?
问题描述:
有什么办法可以改变延迟堆栈?例如,将调用添加到延迟堆栈的底部,还是删除最后放置的延迟?
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
}