How I can iterate data in structure

Gary Willoughby via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Aug 22 04:55:59 PDT 2014


On Friday, 22 August 2014 at 10:44:31 UTC, Marc Schütz wrote:
> On Friday, 22 August 2014 at 08:44:51 UTC, Suliman wrote:
>>>foreach (field; result.tupleof)
>>
>> Why I should here specify type of iterable element, but not 
>> first element that I use for iteration?
>>
>> I mean:
>> foreach (_some_type_possible_enum_ field; result)
>>
>> ?
>
> You mustn't, because your struct could have fields of different 
> types. When you `foreach()` over a tuple, the compiler unrolls 
> the loop body, which allows it to use a (potentially) different 
> type on each iteration.
>
> If you don't want this, and all the fields have the same type, 
> you can iterate over an array made from the fields:
>
>     foreach (field; [result.tupleof]) {
>         writeln(field);
>     }

Or you could implement opApply or range primitives in the struct.

http://ddili.org/ders/d.en/foreach_opapply.html
http://dlang.org/phobos/std_range.html


More information about the Digitalmars-d-learn mailing list