www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Const module globals and static this()

reply "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
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).

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.


T

-- 
Food and laptops don't mix.
Feb 15 2012
parent Timon Gehr <timon.gehr gmx.ch> writes:
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.
Feb 15 2012