delegates with references to local strings

bearophile bearophileHUGS at lycos.com
Sat Jun 2 06:11:47 PDT 2012


Tobias Pankrath:

> How can I store the string of the current iteration with a 
> delegate?

You need to create a closure (D main returns 0 automatically):


import std.stdio, std.string;

void main() {
     auto lines = ["line A", "line B", "line C"];
     void delegate()[] delegates;

     foreach (line; lines) {
         writeln(line);
         delegates ~= ((in string myLine) => { writeln(myLine); 
})(line);
     }

     foreach (deleg; delegates)
         deleg();
}


Bye,
bearophile


More information about the Digitalmars-d-learn mailing list