I don't like slices in D

David Nadlinger code at klickverbot.at
Thu Oct 17 13:12:15 PDT 2013


On Thursday, 17 October 2013 at 19:23:37 UTC, Vitali wrote:
> I repeat "[...] as efficient as manipulating array indices." In 
> D this is not the case and can't imagine what purpose can it 
> suit else.

This is also the case for D.

Without knowing the Go design in detail, I'd say the major 
difference between them is that in D, you can always be sure that 
*extending* a slice never leads to overwriting some memory you 
don't know about:

---
void appendAnswer(int[] data) {
     data ~= 42;
}

void main() {
     auto a = [1, 2, 3, 4];
     auto b = a[0 .. $ - 1];
     void dump() {
         import std.stdio;
         writefln("a = %s, b = %s (%s)", a, b, b.capacity);
     }
     dump();

     // Now let's assume b would still have all the capacity.
     b.assumeSafeAppend();
     dump();

     appendAnswer(b);
     dump();
}
---

The D design makes sure that if your piece of code hands off a 
slice into some buffer, other parts can (by default) never end up 
actually modifying anything but that slice. There is quite a 
benefit to that, design-wise.

David


More information about the Digitalmars-d mailing list