Top level associative arrays

evilrat via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue May 2 03:15:06 PDT 2017


On Tuesday, 2 May 2017 at 09:50:50 UTC, ANtlord wrote:
> On Tuesday, 2 May 2017 at 08:24:09 UTC, evilrat wrote:
>>
>> 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 ... }
>
> I know about D's enums and I know about module ctors but my 
> question is about difference between array and associative 
> array in case of definition in top level of module. Why DMD 
> allows to define array and doesn't allow to define associative 
> array.

Because it is perfectly fine. They are live in the module scope, 
which has its own life time, and from runtime or lifetime 
perspective there is no difference here. And since array can be 
fixed-sized it is valid to use as enum value. But there is one 
catch, in case of enum array it is best to avoid it in favor of 
immutable array* because every time you reference it it will 
allocate. But thats the difference between enum and not enum, not 
the array and map.
This is what I remember from the past, and it is possibly that no 
longer relevant anymore.

* not sure if it prevents allocation though, but in theory it 
should since it *should* go  in to program data section when 
compiling


More information about the Digitalmars-d-learn mailing list