|
|
|
|
|
by nvlled
215 days ago
|
|
It's not the same, defer does not conditionally interrupt the flow of execution, it will always run at the end of a block. If I see a defer, I am absolutely certain that whatever is deferred will run. The same is not true for exceptions. If I am not mistaken defer just moves the code at the end of the block, no jumping is involved. |
|
But destructors also don't conditionally interrupt the flow of execution, and always run at the end of a block.
> If I see a defer
The point is that you're not seeing it. In order to know if there's a defer happening at the end of a function you can't just read the end of the function, you need to read the entire function. That's non-local reasoning, which is what Zig professes to abhor.
And in fact defer is worse than destructors here, because a destructor runs the exact same code every time, whereas defer allows arbitrary code, so you need to review every single usage. And you also need to remember not to forget to use it in the first place (which is the classic footgun with defer), so in addition to vetting everywhere you use it, you also need to vet everywhere you might have forgotten to use it.