September 24, 2019 Why dynamic array is InputRange but static array not. | ||||
---|---|---|---|---|
| ||||
Hi: in phobos/std/range/primitives.d has this code ``` static assert( isInputRange!(int[])); static assert( isInputRange!(char[])); static assert(!isInputRange!(char[4])); static assert( isInputRange!(inout(int)[])); ``` but the dynamic array and static array neither not has popFront/front/empty. https://dlang.org/spec/arrays.html#array-properties properties |
September 24, 2019 Re: Why dynamic array is InputRange but static array not. | ||||
---|---|---|---|---|
| ||||
Posted in reply to lili | On Tuesday, September 24, 2019 1:35:24 AM MDT lili via Digitalmars-d-learn wrote:
> Hi:
> in phobos/std/range/primitives.d has this code
> ```
> static assert( isInputRange!(int[]));
> static assert( isInputRange!(char[]));
> static assert(!isInputRange!(char[4]));
> static assert( isInputRange!(inout(int)[]));
> ```
> but the dynamic array and static array neither not has
> popFront/front/empty.
> https://dlang.org/spec/arrays.html#array-properties properties
Because for something to be a range, it must be possible for it to shrink. popFront works with a dynamic array, because dynamicy arrays have a dynamic size. It's basically just
void popFront(T)(ref T[] a)
{
a = a[1 .. $];
}
However, static arrays have a fixed size, so it's not possible to implement popFront for them. If you want to use a static array as a range, then you need to slice it to get a dynamic array - though when you do that, make sure that the dynamic array is not around longer than the static array, because it's just a slice of the static array, and if the static array goes out of scope, then the dynamic array will then refer to invalid memory.
- Jonathan M Davis
|
Copyright © 1999-2021 by the D Language Foundation