So what do people think about having a feature in the C language akin to the defer statement in GoLang?
The GoLang defer statement defers the execution of a function until the surrounding function returns. The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns. It looks like an interesting mechanism for cleaning up resources.
It could be very useful for cleaning resources. I've never used GoLang, but can see how that could be useful in various circumstances.
As we're talking about C, I suspect a feature like that, with the potential to make things safer, would also enable the unwary to shoot themselves in the foot more easily.
It sounds like the __attribute__((cleanup(…))) already offered by GCC is similar to this. I probably won't have time to investigate the differences while the AMA is ongoing though.
I personally don't like golang's defer. For me it obscures the flow of the program. For example when I acquire a lock, I like to see where exactly it's released.
For me "defer" only makes sense in the context of exceptions, basically as an equivalent to "finally". This is a slippery slope though, since golang's exceptions are, for a reason, rudimentary.
How about deferring until the surrounding block scope ends? In Go you can get around the limitation of defer only executing at the end of a function by wrapping any arbitrary section of code inside an immediately executed anonymous function. But in C I'm not sure that's possible so maybe one could declare a new block scope instead to control when defer kicks in.
The GoLang defer statement defers the execution of a function until the surrounding function returns. The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns. It looks like an interesting mechanism for cleaning up resources.