Closures over temporary variables
bauss
jj_1337 at live.dk
Tue Jun 14 09:04:13 UTC 2022
On Tuesday, 14 June 2022 at 08:26:53 UTC, Anonymouse wrote:
> What is the correct way of making this output `0 1 2`?
>
> ```d
> void delegate()[] dgs;
>
> foreach (immutable i; 0..3)
> {
> dgs ~= () => writeln(i);
> }
>
> foreach (dg; dgs)
> {
> dg(); // outputs: `2 2 2`
> }
> ```
You have to do it like this:
```
dgs ~= ( (n) => () { writeln(n); })(i);
```
Because D hasn't fixed their million dollar mistake after so many
years:
https://issues.dlang.org/show_bug.cgi?id=2043
https://issues.dlang.org/show_bug.cgi?id=23136
More information about the Digitalmars-d-learn
mailing list