static array is not a range

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Jan 9 17:33:55 UTC 2024


On Tuesday, January 9, 2024 6:22:24 AM MST bachmeier via Digitalmars-d-learn 
wrote:
> On Tuesday, 9 January 2024 at 10:11:35 UTC, Alexibu 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.
>
> Jonathan's been giving you good general information about this.
> I'm curious about your partial example. If I fix the writefln
> call, it works.
>
> ```
> import std;
> float[4] arr;
> void main() {
>    arr[0] = 1;
>    arr[1] = 2;
>    arr[2] = 3;
>    arr[3] = 4;
>    arr.each!(a => "%s".writefln(a));
> }
> ```

>From the looks of it, each is explicitly designed to work with anything that
can be iterated with foreach rather than just ranges. So, unlike a normal
range-based functions, it will work directly with a static array (and should
take it by ref to avoid copying) - at least so long as the function that
it's given compiles properly. Personally, I'd just use a foreach loop and
don't see much point in each at all, but looking at its implementation, it
does look like the OP should be able to use it with static arrays in spite
of the fact that they're not ranges

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list