How do I make my class iterable?

Assembly via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 22 09:33:41 PDT 2015


Does D has an equivalent to C#'s iterator 
(https://msdn.microsoft.com/en-us/library/65zzykke.aspx)? if so, 
where can I find it?

What I want is loop over a user-defined class/struct. In case of 
C#, I just implement the IEnumerable and the GetEnumerator() 
methods that's called by the foreach() construct together with 
the yield keyword I "feed" the loop until the moveNext() returns 
false (no next element). The think I've linked has some C# code 
example.

  Something like this:

struct MyStruct
{
    // proper methods/proeperties called by foreach() to iterate
    // over the array
    int[] myarr;
    int = 0;
    int getNext() { return myarr[i]; }
    bool hasNext() { return i == myarr.length; }
}

MyStruct s;
foreach(MyStruct x; s)
{

}

Is this possible?





More information about the Digitalmars-d-learn mailing list