lambda function with "capture by value"
Adam D. Ruppe via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Aug 6 05:50:22 PDT 2017
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.
More information about the Digitalmars-d-learn
mailing list