www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Associative array literal is non-constant?

reply "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
Why does the following code give a compiler error?

	static int[string] table = ["abc":1, "def":2, "ghi":3];

Error message is:

	prog.d:3: Error: non-constant expression ["abc":1,"def":2,"ghi":3]

How is a literal non-constant?


T

-- 
GEEK = Gatherer of Extremely Enlightening Knowledge
Feb 03 2012
parent "Daniel Murphy" <yebblies nospamgmail.com> writes:
A limitation of the current implementation.  Associative arrays are built on 
the heap, and you can't currently build things on the heap and have them 
exist at runtime.

The best current workaround is probably:
static int[string] table;
static this()
{
  table = ["abc":1, "def":2, "ghi":3];
}

or if inside a function:

static int[string] table;
if (!table)
    table = ["abc":1, "def":2, "ghi":3];



"H. S. Teoh" <hsteoh quickfur.ath.cx> wrote in message 
news:mailman.356.1328336206.25230.digitalmars-d-learn puremagic.com...
 Why does the following code give a compiler error?

 static int[string] table = ["abc":1, "def":2, "ghi":3];

 Error message is:

 prog.d:3: Error: non-constant expression ["abc":1,"def":2,"ghi":3]

 How is a literal non-constant?


 T

 -- 
 GEEK = Gatherer of Extremely Enlightening Knowledge 

Feb 03 2012