Hacker News new | past | comments | ask | show | jobs | submit login

> The central idea behind defer is that, unlike its Go counterpart, defer in C is lexically bound, or “translation-time” only, or “statically scoped”. What that means is that defer runs unconditionally at the end of the block or the scope it is bound to based on its lexical position in the order of the program.

The only reasonable way for defer to behave. Function scoped never made sense to me given the wasted potential. The demonstration with loop and mutex being a good one.




Block-based defer is also important when using macros that inserts blocks. They can use defer without care for how nested they are invoked.


yeah, I've always just extracted the loop body into a new function as a result


I've created a lambda and called it inline to force lexically scoped defer semantics. Works fine and reads fine imo.


I've definitely done that as well. I generally don't have a problem with it, but it makes for an extra conversation the first time someone sees the pattern.

Given how some of the other ergonomic changes in go have gone (closures capturing loop variables, for instance), I'd support a change to lexical scoped defers if it were on the table.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: