lambda function with "capture by value"

Simon Bürger via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 6 15:04:07 PDT 2017


On Sunday, 6 August 2017 at 12:50:22 UTC, Adam D. Ruppe wrote:
> On Saturday, 5 August 2017 at 19:58:08 UTC, Temtaime wrote:
>>  		(k){ dgs[k] = {writefln("%s", k); }; }(i);
>
> Yeah, that's how I'd do it - make a function taking arguments 
> by value that return the delegate you actually want to store. 
> (Also use this pattern in Javascript btw for its `var`, though 
> JS now has `let` which works without this trick... and D is 
> supposed to work like JS `let` it is just buggy).
>
> You could also define a struct with members for the values you 
> want, populate it, and pass one of its methods as your 
> delegate. It is syntactically the heaviest but does give the 
> most precise control (and you can pass the struct itself by 
> value to avoid the memory allocation entirely if you want).
>
> But for the loop, the pattern Temtaime wrote is how I'd prolly 
> do it.

I like the (kinda cryptic IMO) look of this '(k){...}(i)' 
construction. But for my actual code I went with struct+opCall 
without any delegate at all.

Anyway, thanks for all your suggestions.


More information about the Digitalmars-d-learn mailing list