Defer in D

Bauss via Digitalmars-d digitalmars-d at puremagic.com
Sun Mar 20 09:18:06 PDT 2016


On Sunday, 20 March 2016 at 14:11:11 UTC, Nick Treleaven wrote:
> On Saturday, 19 March 2016 at 23:16:40 UTC, Xinok wrote:
>>
>> 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
>
> Nice! This is more flexible than Go's defer as you can have 
> more than one stack of them.
>
> I don't quite get this:
>
>> defer((int i) => writeln(i), i);
>
> If it was defer(() => writeln(i)), would that do the same? 
> (Dpaste won't seem to let me edit your example on my tablet).

No that's not the same, since the reference to i does not change 
when doing:
defer(() => writeln(i))

However with defer((int i) => writeln(i), i) you pass the value 
of i to the lambda expression which stores the value in a new 
reference.

The problem with the first one is the value will always be the 
last value of i.


More information about the Digitalmars-d mailing list