Assigning to slice of array

ag0aep6g anonymous at example.com
Thu Mar 1 22:59:03 UTC 2018


On 03/01/2018 11:43 PM, Jamie wrote:
> So if I do
>      arr[0 .. 1][0] = 3;
> shouldn't this return
>      [[3, 0, 0], [0, 0, 0]] ? Because I'm taking the slice arr[0 .. 1], 
> or arr[0], which is the first [0, 0, 0]?

arr[0 .. 1] is not the same as arr[0].

arr[0 .. 1] is not the first element of arr; it's an array that contains 
the first element of arr. It's not [0, 0, 0]; it's [[0, 0, 0]]. It's not 
an int[]; it's an int[][].

> Then assigning the first 
> element to 3?
> instead it returns
>      [[3, 3, 3], [0, 0, 0]]

Since arr[0 .. 1] is [[0, 0, 0]], arr[0 .. 1][0] is [0, 0, 0]. Assigning 
3 to that means assigning to all of its values. And so you get [3, 3, 3].


More information about the Digitalmars-d-learn mailing list