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);
    }
}

opApply和区间参考在此

posted @ 2022-10-25 10:52  zjh6  阅读(28)  评论(0)    收藏  举报  来源