Treating a slice as an InputRange

Ali Çehreli acehreli at yahoo.com
Wed Nov 15 21:14:04 UTC 2017


On 11/15/2017 01:02 PM, Jonathan M Davis wrote:
 > On Wednesday, November 15, 2017 20:53:39 unleashy via Digitalmars-d-learn

 >> ubyte[] slice;
 >> ...
 >> int a = readInt(slice);
 >> double b = readDouble(slice);
 >>
 >> Ends up failing, because readInt properly reads an int, but the
 >> slice is not mutated "outside" of itself

That should work:

import std.range;

T read(T, Range)(auto ref Range range) if (isInputRange!Range) {
     range.popFront();
     return 42;
}

unittest {
     ubyte[] slice = [ 1, 2 ];
     read!int(slice);
     assert(slice == [2]);
}

void main() {
}

 > If you specifically want a function to
 > accept a range and mutate it without returning it, then it should 
take its
 > argument by ref.

Agreed.

Ali



More information about the Digitalmars-d-learn mailing list