I don't like slices in D
Vitali
notavailable at mail.com
Thu Oct 17 11:31:26 PDT 2013
On Thursday, 17 October 2013 at 18:21:30 UTC, David Eagen 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
>> }
>
>
> Change your slice to
> int[] dSlice = dArr[0..$] or [0..3];
>
> The way you are doing it only takes the first 2 elements.
>
> Modified code:
>
> import std.stdio : writeln;
>
> void main()
> {
> int[] dArr = [10, 11, 12];
> int[] dSlice = dArr[0..$];
> assert(dArr[2] is dSlice[2]); // passes
> dSlice.length++;
> assert(dArr[2] == dSlice[2]); // passes
> }
This doesn't answer my question.
I repeat my question: "Why does a reallocation accure AFTER a
resize of the length of a slice, although there is still
capacity?"
More information about the Digitalmars-d
mailing list