The demise of T[new]

bearophile bearophileHUGS at lycos.com
Sun Oct 18 14:34:42 PDT 2009


Walter Bright:

> Andrei had the idea that T[new] could be dispensed with by making a 
> "builder" library type to handle creating arrays by doing things like 
> appending, and then delivering a finished T[] type. This is similar to 
> what std.outbuffer and std.array.Appender do, they just need a bit of 
> refining.

I like how Andrei keeps trying to invent new possible ideas.
Sometimes situations can be improved adding things, and some other times removing things.
So arrays will keep being kinda values, so if inside a function you use an appender to add items to an array, outside the function, when the function returns, you will keep seeing the original shorter array. This is not fully intuitive (but you can get used to it just because you use arrays all the time).

The following code is not possible any more because you can't change the length:

import std.stdio: writefln;
void main() {
    int[] a1 = new int[5];
    a1[] = 1;
    int[] a2 = a1[1..3];
    writefln(a1, " ", a2); // [1,1,1,1,1] [1,1]
    a2.length = a2.length + 4;
    writefln(a1, " ", a2); // [1,1,1,1,1] [1,1,0,0,0,0]
}

But how do you change the length of an array (because appending many single items isn't always what you need to do)?
And how does that interacts with the slicing, as in this code example?

Bye,
bearophile



More information about the Digitalmars-d mailing list