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

Reply via email to