An input range iteration question
ref2401 via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Apr 8 05:50:44 PDT 2015
If Iterator is a struct then Iterator.input won't be adjusted
properly when the foreach loop ends.
Iterator.input still holds "abcde" value.
If i mark Iterator as class then Iterator.input will be an empty
string after the foreach loop.
Could anyone explain me the difference please?
Thank you.
struct Iterator {
string input;
this(string input) {
this.input = input;
}
bool empty() { return input.empty; }
dchar front() { return input.front; }
void popFront() {
if (empty) {
return;
}
input.popFront();
writeln("(iterator.popFront)", input);
}
}
void main(string[] args) {
Iterator iterator = Iterator("abcde");
foreach (dchar c; iterator) {
writefln("%s", c);
}
writefln("(the end): %s", iterator.input);
}
More information about the Digitalmars-d-learn
mailing list