array setting : Whats going in here?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Oct 7 23:12:40 UTC 2023


On Saturday, October 7, 2023 10:59:47 AM MDT claptrap via Digitalmars-d-learn 
wrote:
> On Saturday, 7 October 2023 at 00:49:39 UTC, H. S. Teoh wrote:
> > On Sat, Oct 07, 2023 at 12:00:48AM +0000, claptrap via
> > Digitalmars-d-learn wrote:
> >
> >
> > When you write `foo[]` you're taking a slice of the array, and
> > in that case if the lengths of both sides of the assignment
> > don't match, you'll get a runtime error.
>
> How did I not know that?? I'd always thought "foo[] = x" was just
> special syntax for setting all the elements to the same value.
>
> Thanks.

It is, but it's assigning them to the elements in the slice, and if you
slice the entire array, then you're assigning to every element in the array.
e.g.

    auto foo = new int[](6);
    foo[] = 5;
    assert(foo == [5, 5, 5, 5, 5, 5]);

Alternatively, you can assign to a slice that refers to just some of the
elements of the array being sliced. e.g.

    auto foo = new int[](6);
    foo[0 .. 3] = 5;
    assert(foo == [5, 5, 5, 0, 0, 0]);

And if you're assigning another array to it rather than a value of the
element type, then it assigns the individual elements. e.g.

    auto foo = new int[](6);
    auto bar = [1, 2, 3, 4];
    foo[0 .. 4] = bar[];
    assert(foo == [1, 2, 3, 4, 0, 0]);

And when you assign an array/slice like that, the number of elements on each
side must match. So, if you do any of

foo[] = bar[];

or

foo[] = bar;

then foo and bar must have the same length (and must have compatible element
types). The difference between those and

foo = bar;

is that assigning to foo[] results in the elements being copied, whereas
assigning directly to foo results in foo being a slice of bar.

    auto foo = new int[](6);
    auto bar = new int[](6);
    foo[] = bar[];
    assert(foo == bar);
    assert(foo !is bar);
    foo = bar[];
    assert(foo is bar);

So, it's probably best to think of

foo[] = x;

as being a way to assign to each individual element in that slice of foo
rather than assigning to foo. And then which elements are assigned to
depends on how much of foo you slice, and how those elements are assigned to
depends on the type of x.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list