Top level associative arrays

evilrat via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue May 2 01:24:09 PDT 2017


On Tuesday, 2 May 2017 at 07:48:35 UTC, ANtlord wrote:
> Hello! Is it possible to define associative array on top level 
> of module?
> I try to compile this code and I get message `Error: 
> non-constant expression ["s":"q", "ss":"qq"]`
>
> import std.stdio;
>
> auto dict = [
> 	"s": "q",
> 	"ss": "qq"
> ];
> void main()
> {
> 	writeln(val);
> }
>
> I solved it by replacement of word `auto` by `enum`. It is 
> acceptable for me. But I notice some inconsistency of logic. 
> When I define simple array I don't get same compile error and 
> it doesn't lead to define this array using enum. What is key 
> difference between them in this case?
>
> Thanks. Sorry if my English is not clear.

Making enum means that value should be available at compile time 
and AA's are fully dynamic. But if my memory serves me well, you 
can declare empty AA and delay initialization. So the closest 
solution is to move initialization of AA to shared module 
ctor(note that there is difference between shared and non-shared, 
refer to documentation) such as in this example:
--------------------------------

static shared this() // <-- module ctors run before main()
{
  dict = [
    "s": "q",
    "ss": "qq"
  ];
}

string[string] dict;

void main()
{ ... dict is already initialized ... }


More information about the Digitalmars-d-learn mailing list