I don't like slices in D

Vitali notavailable at mail.com
Thu Oct 17 11:41:52 PDT 2013


On Thursday, 17 October 2013 at 18:29:47 UTC, John Colvin wrote:
> 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
>>  }
>
> What's the use case for this? I haven't found myself ever 
> needing something like that so far, but i'd be open to seeing 
> an example.

The use case is:

void appendElement(ref int[] arr, int x) {
   arr ~= x;
}

void removeElement(ref int[] arr, int index) {
   arr = arr[0..index] ~ arr[index+1..$];
}

void main() {
   int[] arr = [1, 2, 3];
   arr.reserve(7);       // Reserve capacity.
   arr.appendElement(4); // Here should be
   arr.removeElement(1); // no realocation of array,
   arr.appendElement(5); // but it is.
   assert(arr[1] == 3);
   assert(arr[2] == 4);
   assert(arr[3] == 5);
}

But maybe I don't understand what slices are for in D. Anyway in 
Go this works whithout reallocation.


More information about the Digitalmars-d mailing list