static array is not a range

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Jan 9 10:44:34 UTC 2024


On Tuesday, January 9, 2024 3:11:35 AM MST Alexibu via Digitalmars-d-learn 
wrote:
> It looks like isInputRange is false for arrays with fixed length
> by design.
>
> I can do:
>
> ```d
> float[4] arr;
> foreach(x;arr)
>     writefln("%s",x)
> ```
> but not :
>
> ```d
> arr.each!(a => a.writefln("%s",a));
> ```
> Is there a good reason for this ?
> It took my a long time to figure out.

How would it even be possible for a static array to be a range? It has a
fixed length. For a type to work as a range, it needs to be possible to pop
elements off of it, which you can't do with a static array. Input ranges
must have front, popFront, and empty. Dynamic arrays have that from
std.range.primitivies via UFCS (Universal Function Call Syntax), and that
works, because it's possible to shrink a dynamic array, but it won't work
with a static array, because its size will be fixed.

Now, what you can do is slice a static array to get a dynamic array which
refers to the static array. And since dynamic arrays work as ranges, you can
use that with range-based functions. That being said, you do then have to be
careful about the dynamic array (or any ranges which wrap it) escaping from
the scope where the static array is, because if the static array goes out of
scope and is destroyed, then any dynamic arrays referring to it will be
referring to invalid memory, and you'll get undefined behavior. So, while
slicing static arrays can be very useful, it needs to be done with caution.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list