Defer in D

Xinok via Digitalmars-d digitalmars-d at puremagic.com
Sat Mar 19 16:16:40 PDT 2016


I stumbled upon an example demonstrating defer in Go which I 
thought was interesting. Defer is similar to scope in D except 
they're called at end of function rather than end of scope; you 
can queue multiple defer calls by writing them inside of a loop. 
This implies that it internally builds a stack of delegates which 
are then executed LIFO once the function returns (or panics).

https://tour.golang.org/flowcontrol/13

I took a quick look through Phobos but didn't see anything 
similar so I wrote this as a proof of concept and to elicit 
discussion. This also works should the function throw rather than 
return gracefully.

http://dpaste.dzfl.pl/23c665bdae9e

I think a library solution is elegant enough that it doesn't need 
to be built into the language but that doesn't mean it needs to 
be in Phobos either. Does anybody have a use case for "defer" 
that isn't already adequately covered by scope statements?


More information about the Digitalmars-d mailing list