Referencing structs in a foreach
Peter Alexander via Digitalmars-d
digitalmars-d at puremagic.com
Wed Jul 23 10:35:16 PDT 2014
On Wednesday, 23 July 2014 at 17:23:14 UTC, Alf wrote:
> Thanks for your reply.
> I figured an easier way would be to simply build an array of
> references:
>
> foreach (ref f; [&bar.f1, &bar.f2])
> {
> f.a++;
> f.b++;
> }
>
> It seems to work just fine.
I'd recommend using std.range.only:
foreach (ref f; only(&x, &y)) {
f.a++;
f.b++;
}
Using array literals introduces the possibility of an unnecessary
heap allocation. Using only will never allocate.
More information about the Digitalmars-d
mailing list