Indexed foreach on struct?
Ali Çehreli
acehreli at yahoo.com
Mon Jan 23 13:26:44 PST 2012
On 01/23/2012 01:16 PM, H. S. Teoh wrote:
> On Mon, Jan 23, 2012 at 03:32:07PM -0500, Matt Soucy wrote:
>> So I was messing around with some code I've been writing recently,
>> and I wanted to use a foreach on a struct as if it were an
>> associative array. The problem is, I can't find any information on
>> how to do that.
> [...]
>> I don't see any sort of opApply or similar to do this, and the
>> foreach section of dlang.org doesn't help. Is there a way to do it,
>> or do I need to do a workaround?
> [...]
>
> You can use opApply.
And potentially more than one overload to match the foreach loop variables.
> Sample test program:
>
> struct Test {
> int opApply(int delegate(ref int) dg) {
> auto ret = 0;
> for (auto i=0; ret==0&& i<5; i++) {
> ret = dg(i);
Add:
if (ret) {
break;
}
ret is non-zero if the foreach body contains a break statement.
> }
> return ret;
> }
> }
>
> import std.stdio;
> void main() {
> Test t;
>
> foreach (n; t) {
> writeln(n);
> }
> }
>
> Program prints:
>
> 0
> 1
> 2
> 3
> 4
>
> Hope that helps.
>
>
> T
>
Ali
More information about the Digitalmars-d-learn
mailing list