News and problems about foreach loops

bearophile bearophileHUGS at lycos.com
Sat Nov 3 08:50:57 PDT 2012


Peter Alexander:

> I'm not a fan of introducing new keywords or introducing 
> breaking changes in D code (even though I don't use Case3). I 
> think this might just be something we have to live with,

Using a custom property is maybe acceptable (this @copy doesn't 
need to be a built-in, probably it's not too much hard to define 
it with user-defined attributes):


void main() {
     auto data = [0, 1, 2, 3];
     foreach (@copy x; data)
         x++;
}


But there are other solutions, like asking D tool (like D IDEs or 
future D lints) to show a warning here.

Another solution is to require an already present keyword ("new" 
means it's a copy, it's not related to heap allocations) for the 
Case3:

void main() {
     auto data = [0, 1, 2, 3];
     foreach (new x; data)
         x++;
}

Bye,
bearophile


More information about the Digitalmars-d mailing list