Static initialization of associative arrays

Ali Çehreli acehreli at yahoo.com
Thu Mar 11 18:41:08 UTC 2021


On 3/11/21 10:06 AM, Chris Piker wrote:

 >    https://dlang.org/spec/hash-map.html#static_initialization
 >
 > that this feature is not yet implemented.

I use a shared static this() block:

immutable string[int] aa;

shared static this() {
   aa = [ 1: "one" ];
}

void main() {
   assert(aa.length == 1);
}

And it is possible to build an AA at compile time as the initial value 
but it still needs a trivial assigment to the immutable variable. 
Assuming that we have the following file at compile time named 'my_aa':

--- 8< ---
1 one
2 two
--- 8< ---

And remembering that we have to use the -J switch when compiling (e.g. 
as -J.), you can parse and build an AA from that file like this. (Sorry 
for insisting on the the range style; it can be done in other ways).

immutable string[int] aa;

shared static this() {
   import std.algorithm;
   import std.range;
   import std.typecons;
   import std.conv;

   enum compileTimeAA = import("my_aa")
                        .splitter
                        .chunks(2)
                        .map!(a => tuple(a.front.to!int,
                                         a.dropOne.front))
                        .assocArray;

   aa = compileTimeAA;
}

import std.stdio;

void main() {
   writeln(aa);
}

Ali



More information about the Digitalmars-d-learn mailing list