原文 如何實作疊代
構/類
?這樣:
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);
}
}
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);
}
}