Sometimes, when iterating over a tuple representation of a class or struct, I want to modify the class/struct contents. Ex:
struct S {
uint foo = 1;
}
void main() {
S s;
foreach(element; s.tupleof)
element = 2;
writeln(s.foo); //Still prints 1
}
It would be nice if I could do something like:
foreach(ref element; s.tupleof)
and this would modify s.foo.
Comment #1 by dsimcha — 2009-06-02T05:51:21Z
*** Issue 3045 has been marked as a duplicate of this issue. ***
Comment #2 by bearophile_hugs — 2010-03-07T10:28:09Z
Bug 3835 is a partial duplicate of this (one case seems different).
Comment #3 by hoganmeier — 2010-05-20T15:12:01Z
This is a workaround:
foreach (i, dummy ; s.tupleof)
s.tupleof[i] = 2;
My patch requires explicit 'ref'.
void main() {
S s;
// foreach( element; s.tupleof) // doesn't work
foreach(ref element; s.tupleof) // OK
element = 2;
assert(s.foo == 2);
}
Comment #6 by dsimcha — 2012-01-01T13:44:46Z
(In reply to comment #5)
> My patch requires explicit 'ref'.
>
> void main() {
> S s;
> // foreach( element; s.tupleof) // doesn't work
> foreach(ref element; s.tupleof) // OK
> element = 2;
> assert(s.foo == 2);
>
(In reply to comment #5)
> My patch requires explicit 'ref'.
>
> void main() {
> S s;
> // foreach( element; s.tupleof) // doesn't work
> foreach(ref element; s.tupleof) // OK
> element = 2;
> assert(s.foo == 2);
> }
It seems to me like the only logical way to do this is to require explicit ref. The semantics should be the same as foreach over ranges. Nice work.