Const module globals and static this()

Timon Gehr timon.gehr at gmx.ch
Wed Feb 15 10:35:34 PST 2012


On 02/15/2012 07:29 PM, H. S. Teoh wrote:
> Why doesn't this compile?
>
> 	const int map[dstring];
> 	static this() {
> 		map["abc"] = 123;
> 	}
>
> It seems utterly pointless to be able to declare a const associative
> array yet be unable to initialize it (trying to initialize it with an AA
> literal doesn't work, the compiler complains the literal is
> non-constant).
>

Do it like this:

immutable int[dstring] map;
static this(){
     map = ["abc": 123];
}

Or like that:

immutable int[dstring] map;
static this(){
     auto foo()pure{
         int[dstring] r;
         r["abc"]=123;
         return r;
     }
     map	= foo();
}


> AA's are a very welcome inclusion in D (IMNSHO, no modern programming
> language worth its salt should omit AA's), but they do have some aspects
> that are utterly annoying.
>

Those aspects will go away once they can be initialized at compile time.


More information about the Digitalmars-d-learn mailing list