Gotcha with const std.range.chunks
H. S. Teoh
hsteoh at quickfur.ath.cx
Thu Jul 30 19:15:36 UTC 2020
On Thu, Jul 30, 2020 at 06:52:42PM +0000, sportsracer via Digitalmars-d-learn wrote:
[...]
> int[] xs = new int[100];
> const chunked = xs.chunks(10);
> writeln(chunked[0][0]);
> }
>
> Error: mutable method std.range.Chunks!(int[]).Chunks.opIndex is not
> callable using a const object
In order to iterate the chunks, you must be able to mutate the range
object returned by .chunks. If it's const, then it's not mutable, and
therefore it cannot be iterated.
If you want to protect the underlying data from mutation, create a const
view of the data first, e.g., something like this:
int[] xs = new int[100];
const(int)[] constView = xs;
auto chunked = constView.chunks(10); // N.B. mutable
The range itself will be mutable, but the elements will be const and not
mutable through the range.
T
--
Why can't you just be a nonconformist like everyone else? -- YHL
More information about the Digitalmars-d-learn
mailing list