Delegates and values captured inside loops

ryuukk_ ryuukk.dev at gmail.com
Sat Jan 20 16:53:12 UTC 2024


On Saturday, 20 January 2024 at 15:59:59 UTC, Anonymouse wrote:
> I remember reading this was an issue and now I ran into it 
> myself.
>
> ```d
> import std.stdio;
>
> void main()
> {
>     auto names = [ "foo", "bar", "baz" ];
>     void delegate()[] dgs;
>
>     foreach (name; names)
>     {
>         dgs ~= () => writeln(name);
>     }
>
>     foreach (dg; dgs)
>     {
>         dg();
>     }
> }
> ```
>
> Expected output: `foo`, `bar`, `baz`
> Actual output:   `baz`, `baz`, `baz`
>
> If I make `names` an `AliasSeq` it works, but I need it to be a 
> runtime array.
>
> Is there a workaround?


```d
import std.stdio;

void main()
{
     auto names = [ "foo", "bar", "baz" ];
     void delegate()[] dgs;


     foreach (name; names)
     {
         (it) {
             dgs ~= () => writeln(it);
         }(name);
     }

     foreach (dg; dgs)
     {
         dg();
     }
}
```

This is the workaround according to: 
https://issues.dlang.org/show_bug.cgi?id=21929#c9





More information about the Digitalmars-d-learn mailing list