d迭代构或类的示例
原文
 如何实现迭代构/类?这样:
foreach (k, v; T.init)
{
    ...
}
 
T.byKeyValue没用.
你应该用opApply.示例:
struct A {
    static int[string] impl;
    static this() {
        impl = [
            "a": 1,
            "b": 2,
        ];
    }
    int opApply(scope int delegate(string a, int b) dg) {
        foreach (k, v; impl) {
            auto r = dg(k, v);
            if (r) return r;
        }
        return 0;
    }
}
void main() {
    import std;A a;
    foreach (k, v; a) {
        writefln("%s -> %s", k, v);
    }
}
 
或使用front()返回元组的区间函数.D有个特性,在foreach循环中自动展开元组:
import std.typecons : tuple;
import std.conv : to;
import std.stdio : writeln;
import std.range : take;
struct S {
    size_t count;
    bool empty = false;
    auto front() {
        const key = count;
        const value = key.to!string;
        return tuple(key, value);// 在此
    }
    void popFront() {
        ++count;
    }
}
void main() {
    foreach (k, v; S.init.take(10))
    {
        writeln(k, ": ", v);
    }
}
 
                
                
            
        
浙公网安备 33010602011771号