I don't like slices in D

David Eagen davideagen at mailinator.com
Thu Oct 17 11:21:29 PDT 2013


On Thursday, 17 October 2013 at 18:00:20 UTC, Vitali wrote:
> I expected slices to be in D (http://dlang.org/arrays.html) 
> like they are in Go 
> (http://blog.golang.org/go-slices-usage-and-internals). But 
> they are not.
>
> Why the array have to be reallocated after the length of a 
> slice is changed? It makes slices useless.
>
> Here a little example (it fails):
>
>   void testSlices() {
>     int[] dArr = [10, 11, 12];
>     int[] dSlice = dArr[0..2];
>     dSlice.length++;
>     assert(dArr[2]==dSlice[2]); // failure
>   }


Change your slice to
int[] dSlice = dArr[0..$] or [0..3];

The way you are doing it only takes the first 2 elements.

Modified code:

import std.stdio : writeln;

void main()
{
   int[] dArr = [10, 11, 12];
   int[] dSlice = dArr[0..$];
   assert(dArr[2] is dSlice[2]); // passes
   dSlice.length++;
   assert(dArr[2] == dSlice[2]); // passes
}


More information about the Digitalmars-d mailing list