5

The following declaration:

const(string[char]) AA1 = [
    'a' : "fkclopel",
    'b' : "poehfftw"
];

void main(string args[]){}

gives me:

C:...\temp_0186F968.d(1,27): Error: non-constant expression ['a':"fkclopel", 'b':"poehfftw"]

while it would work with other type kinds.

1 Answer 1

7

You can initialize associative array constants inside a module constructor:

const /+ or immutable +/ (string [char]) AA1;
static this () {
    AA1 = [
        'a' : "fkclopel",
        'b' : "poehfftw"
    ];
}

import std.stdio;
void main () {writeln (AA1);}

The manual section on associative array literals explicitly states that "An AssocArrayLiteral cannot be used to statically initialize anything.", though it does not give clues as to why it is so.

2
  • 8
    The reason is that in the current implementation (which is suboptimal in a number of ways), the associative array layout and other details are completely opaque to the compiler. An AA literal just calls a runtime function (file src/druntime/src/rt/aaA.d, function _d_assocarrayliteralTX) which is responsible for actually organizing the data. That function might not even exist at compile time, being linked later from a binary library. Since static data needs a known layout so the compiler can put it into the executable's data segment and this function is a black box, it can't be used for that. Commented Nov 11, 2014 at 14:41
  • 1
    It should be noted that this restriction will eventually go away, once there is a solid library implementation of associative arrays. There is currently work in progress to this effect, which seems to be nearing completion.
    – Meta
    Commented Nov 14, 2014 at 17:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.