Closures over temporary variables

Ali Çehreli acehreli at yahoo.com
Tue Jun 14 15:45:16 UTC 2022


On 6/14/22 02:04, bauss wrote:

 > You have to do it like this:
 >
 > ```
 > dgs ~= ( (n) => () { writeln(n); })(i);
 > ```

The same thing with a named function as well as with iota():

import std.range;
import std.algorithm;
import std.stdio;

void main() {
   void delegate()[] dgs;

   auto makeDg(int i) {
     return () => writeln(i);
   }

   foreach (immutable i; 0 .. 3)
   {
     dgs ~= makeDg(i);
   }

   iota(3).each!(i => dgs ~= () => writeln(i));

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

Ali



More information about the Digitalmars-d-learn mailing list