How do I make my class iterable?

q66 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 22 09:37:49 PDT 2015


On Monday, 22 June 2015 at 16:33:43 UTC, Assembly wrote:
> 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?

use opApply.


More information about the Digitalmars-d-learn mailing list