I don't like slices in D
Ali Çehreli
acehreli at yahoo.com
Thu Oct 17 11:55:30 PDT 2013
On 10/17/2013 11:41 AM, Vitali wrote:
> 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;
That will not allocate if there is capacity.
> }
>
> void removeElement(ref int[] arr, int index) {
> arr = arr[0..index] ~ arr[index+1..$];
It must necessarily allocate, right? How does Go deal with that case?
However, I see that the capacity of arr after that operation is just 3!
Since a new array is allocated by the runtime, the capacity of arr could
be larger as well.
Perhaps that's the only problem here. (?)
> }
>
> 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.
Ali
More information about the Digitalmars-d
mailing list