Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I like the idea of the `defer `keyword - you can have automatic cleanup at the end of the scope but you have to make it obvious you are doing so, no hidden execution of anything (unlike c++ destructors).




Adopted from go, first appeared in D, invented by one of its major developers, Andrei Alexandrescu.

P.S. In D it's `scope(exit)` = defer, `scope(failure)` = Zig's errdefer, and `scope(success)` -- which no one else has and which I have made good use of. e.g., I have a mixin that traces entry and exit from a function, the latter with scope(success). If I use scope(exit) instead then when an exception is thrown all the leave messages are printed and then the stack trace, rather than seeing the stack trace at the point of failure (this baffled me when it first happened).

I vaguely remember reading somewhere recently that Andrei left the D community / foundation. Do you know if that is true?


But you can forget it, unlike C++ destructors

The GNU C and C++ dialect also has attribute cleanup. https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attribute...

I would like a language to support both defer and C++ style destructors / Rust Drop. There are good use-cases for having both. For things like a mutex or straight-forward resource cleanup - having a bunch of brain-dead defer statements adds little value and only bloats unnecessary line count. Let the resource type handle its own release/cleanup at scope close. Code is made sweet, succinct and safe.

In Rust, there’s a drop guard pattern to do this, which leverages the lazy execution of closure, checkout the scopeguard crate. C++ should be easy to do that too I think

GNU C++?

C++ doesn't have hidden execution, you just don't know the language. Once you exit scope destructor is invoked.



Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

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

Search: