Error with associative array initializer DMD32 D Compiler v2.070.0

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Mar 3 14:55:29 PST 2016


On 03/03/2016 05:17 AM, Andrew Edwards wrote:
 > On 3/3/16 7:01 PM, MGW wrote:
 >> immutable long[string] aa = [
 >>     "foo": 5,
 >>     "bar": 10,
 >>     "baz": 2000
 >> ];
 >
 > The only way this can be done outside the body of a function is if it is
 > a manifest constant. This works:
 >
 > enum long[string] aa = [
 >      "foo": 5,
 >      "bar": 10,
 >      "baz": 2000
 > ];

With the caveat that 'aa' is a manifest constant, meaning that its 
values will be placed everywhere 'aa' appears in code. So, the following 
loop *creates* an associative array at avery iteration:

     while (/* ... */) {
         if (aa[s] == 5) {  // <-- oops :(
             // ...
         }
     }

I think initializing it in a 'shared static this()' (or 'static this()') 
block is better:

immutable long[string] aa;

shared static this() {
     aa = [
         "foo": 5,
         "bar": 10,
         "baz": 2000
     ];
}

void main() {
     assert(aa["foo"] == 5);
}

Ali



More information about the Digitalmars-d-learn mailing list