Difference between slice[] and slice

ag0aep6g anonymous at example.com
Wed Sep 25 21:05:45 UTC 2019


On 25.09.19 22:36, WhatMeWorry wrote:
> On Wednesday, 25 September 2019 at 19:25:06 UTC, Ali Çehreli wrote:
>> On 09/25/2019 12:06 PM, WhatMeWorry wrote:
[...]
>> > In short, is there anytime that one would want to use
>> "slice[] =
>> > something" syntax?I
>>
>> That changes element values.
> 
> Ok.  But which element(s)?

All of them. For example, `slice[] = 42;` sets all elements to 42. And 
`slice[] = another_slice[];` replaces all elements of `slice` with 
copies of `another_slice`'s elements.

>  In my specific case, I was using []. Is
> 
> waste[] = waste[0..$-1];
> 
> even semantically meaningful?  Because the LDC compiler had no problem 
> compiling it.

It's equivalent to this:

----
waste[0] = waste[0..$-1][0];
waste[1] = waste[0..$-1][1];
...
waste[waste.length - 2] = waste[0..$-1][waste.length - 2];
waste[waste.length - 1] = waste[0..$-1][waste.length - 1];
----

So it basically does nothing. It just copies `waste`'s elements over 
themselves.

Except that the last line makes an out-of-bounds access. That's an error 
that may be detected during compilation or at run time. Or if you're 
telling the compiler to optimize too aggressively, it might go unnoticed.


More information about the Digitalmars-d-learn mailing list