Assigning to slice of array

Steven Schveighoffer schveiguy at yahoo.com
Fri Mar 2 14:15:55 UTC 2018


On 3/1/18 5:59 PM, ag0aep6g wrote:
> 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[][].

Minor correction, it's actually an int[3][].

Try arr[1 .. 2][0] = 3; It will affect the second static array.

I understand what you really want is the first element of each static 
array. There is no supported syntax for arrays to slice like that. This 
is where ndslice comes in.

But if it *were* supported, it would look like this instead (I think 
this is how ndslice would work, but I've never used it):

arr[0 .. 2, 0] = 3;

The thing I think you are missing is that the expression stops at the 
closing bracket.

In other words arr[0 .. 2][0] is really (arr[0 .. 2])[0].

arr[0 .. 2] is a slice of the original array, which happens to be the 
entire array. So it really doesn't get you anything.

One final note. If you don't want to use array assignment operators, and 
don't mind using ranges, you can do what you want this way:

https://run.dlang.io/is/AdikEE

-Steve


More information about the Digitalmars-d-learn mailing list