Associative array literal. Why doesn't it compile?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 13 23:57:38 PDT 2015


On 08/13/2015 11:48 PM, Adel Mamin wrote:
> Compiler dmd_2.068.0-0_amd64.deb on Ubuntu 12.04 Linux:
>
> auto lookup = [ "one":1, "two":2 ];
>
> The dmd error:
> Error: non-constant expression ["one":1, "two":2]

I think the problem is when the variable is defined at module scope. It 
works inside functions, etc.

> Why doesn't it compile?
> As a workaround I could do the assignment one element at a time in a
> loop. It would be uglier though.

A better workaround is to initialize it in the module constructor:

immutable int[string] lookup;

shared static this()
{
     lookup = [ "one":1, "two":2 ];
}

void main()
{
     assert("one" in lookup);
}

Ali



More information about the Digitalmars-d-learn mailing list