I don't like slices in D

Ali Çehreli acehreli at yahoo.com
Thu Oct 17 11:33:00 PDT 2013


On 10/17/2013 11:00 AM, Vitali wrote:

 > I expected slices to be in D (http://dlang.org/arrays.html)

There is also this article:

   http://dlang.org/d-array-article.html

 > like they
 > are in Go (http://blog.golang.org/go-slices-usage-and-internals). But
 > they are not.

Every design comes with pros and cons. Go's slices can do that because 
they consis of three members: pointer, length, and capacity. Apparently 
they also know the actual array that they provide access to.

D slices have only the first two of those members. (However, the 
capacity can still be obtained by the function capacity(), which is 
ordinarily called with the property syntax.)

 > Why the array have to be reallocated after the length of a slice is
 > changed?

The effect of incrementing length is adding an element to the end. Since 
slices don't own the underlying array elements, in order to preserve the 
potential element beyond their current end, the entire slice gets 
relocated. As described in the article above, this does not happen every 
time.

 > It makes slices useless.

Slices have been very useful so far. Slices do have some gotchas, 
neither of which have been showstoppers.

 > Here a little example (it fails):
 >
 >    void testSlices() {
 >      int[] dArr = [10, 11, 12];
 >      int[] dSlice = dArr[0..2];
 >      dSlice.length++;

That operation has a potential of relocating the slice. You can check 
whether that will be the case:

     if (slice.capacity == 0) {
         /* Its elements would be relocated if one more element
          * is added to this slice. */

         // ...

     } else {
         /* This slice may have room for new elements before
          * needing to be relocated. Let's calculate how
          * many: */
         auto howManyNewElements = slice.capacity - slice.length;

         // ...
     }

 >      assert(dArr[2]==dSlice[2]); // failure
 >    }

Ali



More information about the Digitalmars-d mailing list