Array literals

bearophile bearophileHUGS at lycos.com
Wed Oct 15 17:08:20 PDT 2008


By default arrays/strings in D1 are static:

import std.stdio: writefln;
void main() {
    auto a = ["Hello", "what"];
    writefln(a[2].length); // 5
}

To remove a significant amount of bugs from my code, like that one (the second string is a static array of length 5) I suggest to "invert" the meaning of array literals: by default they define dynamic arrays/strings allocated on the heap (immutable too, if necessary). So a different and explicit syntax can be used/invented to denote static arrays.

So this literal defines a dynamic array of heap-allocated strings:
auto a = ["Hello", "what"];

A possible syntax to allocate a fixed size array of (immutable) fixed size arrays of chars:
string[auto][auto] a = ["Hello", "what"];

This goes well with the usual D philosophy of "safety".

Bye,
bearophile



More information about the Digitalmars-d mailing list