Static initialization of associative arrays

Imperatorn johan_forsberg_86 at hotmail.com
Thu Mar 11 19:31:28 UTC 2021


On Thursday, 11 March 2021 at 18:41:08 UTC, Ali Çehreli wrote:
> 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

You can however do like this (cheating):
https://run.dlang.io/is/9TSfAB

"The variable myOptions is assigned the result of the literal at 
runtime. But because it's immutable, the compiler knows what's in 
it. So it can extrapolate back to the literal what it is at 
compile time"

We had a discussion in Discord about this last week.




More information about the Digitalmars-d-learn mailing list