www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why dynamic array is InputRange but static array not.

reply lili <akozhao tencent.com> writes:
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
Sep 24 2019
parent Jonathan M Davis <newsgroup.d jmdavisprog.com> writes:
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
Sep 24 2019