How to make a global immutable associative array?

Infiltrator Lt.Infiltrator at gmail.com
Tue Mar 18 17:20:41 PDT 2014


On Wednesday, 19 March 2014 at 00:16:31 UTC, dnspies wrote:
> I want to create a global immutable associative array and have 
> it be accessible from anywhere at compile-time.  How can I do 
> that?
>
> With:
> immutable int[int] aa = [1:2,3:4];
>
> I get:
> source/thing.d(1): Error: non-constant expression [1:2, 3:4]
>
> And with:
> immutable int[int] aa;
>
> static this(){
> 	aa = [1:2,3:4];
> }
>
> int c = aa[3];
>
> I get:
> source/thing.d(7): Error: static variable aa cannot be read at 
> compile time
>
> Also associative arrays don't seem to have a .idup
>
> Is there any other way to do this?


You just have to construct it first and then claim that it is 
unique and so safely cast it to immutable:


import std.exception : assumeUnique;

immutable int[int] aa;

static this(){
    auto temp = [1:2, 3:4];
    aa = assumeUnique(temp);
}


More information about the Digitalmars-d mailing list