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
  }

As David Eagen said, your problem is that in D, dArr[0..2] is not inclusive, it's exclusive, so you get dArr[0] and dArr[1]. Changing it to dSlice = dArr[0..3] will work (or better, dArr[0..$]). However, there's something else going on here that's fishy:

void testSlices()
{
        int[] dArr = [10, 11, 12];
        int[] dSlice = dArr[0..2];
        writeln(dArr.ptr, " ", dArr.capacity, " ", dArr.length);
        writeln(dSlice.ptr, " ", dSlice.capacity, " ", dSlice.length);

        dSlice.length++;
        writeln(dSlice.ptr, " ", dSlice.capacity, " ", dSlice.length);

        writeln(dArr);
        writeln(dSlice);
}

4002DFF0 3 3
4002DFF0 0 2
4002DFE0 3 3
[10, 11, 12]
[10, 11, 0]

dSlice says that it has length 2, but accessing dSlice[2] does not produce a RangeError... Likewise, printing it out prints 3 elements, not 2. This looks like a bug to me.

Reply via email to