|
|
|
|
|
by rollulus
499 days ago
|
|
Say that the defer would execute inside for loops, what would make you more astonished: loops and functions are the exceptions, or defers execute at the end of any block? I would prefer the latter of these two. But then the consequence is that a defer in an if-block executes instantly, so you cannot conditionally defer anymore. So it seems that the rules for when deferees execute need to be arbitrary, and "only functions" seems fewer exceptions than "only functions and loops", isn't it? And what about loops implemented through gotos? Oh boy. |
|
I think you can, for example this way:
- declare a function pointer variable cleanup - initialize it with no_op - call defer ‘call cleanup’ - if, inside a block, you realize that you want to do something at cleanup, set cleanup to another function
That’s more code, but how frequent is it that one wants to do that?
One thing this doesn’t support is having a call into third party code defer cleanup to function exit time. Does golang supports that?