Hacker News new | ask | show | jobs
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.
2 comments

> so you cannot conditionally defer anymore.

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?

> a defer in an if-block executes instantly, so you cannot conditionally defer anymore.

Of course you can, using ?: (or && and || if you prefer), just like any other case where you want an expression rather than a statement. Or simply using the non-block form of if. (Some stupid autoformatters or tech leads insert extraneous braces, but you should be avoiding those already).

The parent I was replying to was talking about Go. There is no ternary operator in Go. There are no non-block forms of if in Go. I'm not sure what your "of course" is referring to, but I guess it is unrelated.
I figured we were talking about C since that's the main topic. In any case short-circuit && and || still work in Go AIUI, so my point stands.