1 回答
TA贡献1777条经验 获得超3个赞
defer是 aLIFO或堆栈 - 保证以相反的顺序执行。它获取第一个defer并将其放在某个内部堆栈(可能,我不知道血淋淋的细节),然后将下一个defer放在那个之上,然后当它到达函数的末尾时,它展开,开始在顶部。它似乎是在一个for-loop 中设计的(我知道这是 Go 的示例,而不是您的示例),但在其他情况下,一个函数依赖于其他函数的清理,为什么它应该是更有意义的,因此是,保证是相反的执行顺序。
这是一个不同的示例,所有伪代码,但希望这一点很清楚。
open stream1
defer close stream1
defer write stream1 "stream2 better be closed, or we are in trouble..."
open stream2
defer close stream2
defer stream2 "this is the last you'll ever hear from stream2"
connect stream2 to stream1
write stream2 "hey, we are in stream2, this feeds into stream1"
应该打印如下内容:
"hey, we are in stream2, this feeds into stream1"
"this is the last you'll ever hear from stream2"
"stream2 better be closed, or we are in trouble..."
如果您没有关于反向排序的保证,您无法确定stream1在您的defer stream2 write.
- 1 回答
- 0 关注
- 145 浏览
添加回答
举报