www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - static initialization of associative arrays

reply "Tyro[a.c.edwards]" <nospam home.com> writes:
Is it yet possible to statically initialize an associative array? If so, 
please point me to the documentation. I am using DMD v2.028.

Currently I'm able to do this:

import std.stdio;

string[string] types;
static this(){
     types = [ "void":"void", "bool":"bool" ];
}

void main(){
     writeln(types);
}

Output = [void:void,bool:bool] which is exactly what I want.

However, removing static this() results in an error.

string[string] types = [ "void":"void", "bool":"bool" ];

Result:
api.d(77): Error: non-constant expression ["void":"void","bool":"bool"]

How do I make the initialization constant?

Thanks,
Andrew
Apr 15 2009
next sibling parent novice2 <sorry noem.ail> writes:
may be you can raplace string with char[] ?
Apr 15 2009
prev sibling parent reply Daniel Keep <daniel.keep.lists gmail.com> writes:
Tyro[a.c.edwards] wrote:
 Is it yet possible to statically initialize an associative array? If so,
 please point me to the documentation. I am using DMD v2.028.
 
 Currently I'm able to do this:
 
 import std.stdio;
 
 string[string] types;
 static this(){
     types = [ "void":"void", "bool":"bool" ];
 }
 
 void main(){
     writeln(types);
 }
 
 Output = [void:void,bool:bool] which is exactly what I want.
 
 However, removing static this() results in an error.
 
 string[string] types = [ "void":"void", "bool":"bool" ];
 
 Result:
 api.d(77): Error: non-constant expression ["void":"void","bool":"bool"]
 
 How do I make the initialization constant?
 
 Thanks,
 Andrew
I think Walter said something a while back to the effect that making it possible to statically initialise AAs isn't feasible because it requires setting up a complex structure on the heap. The best you could do would be to *pretend* to statically initialise them, and actually really initialise them in a module ctor. Which is exactly what you currently have to do. Could be wrong; that's just what I remember from the last time this came up. -- Daniel
Apr 15 2009
parent reply bearophile <bearophileHUGS lycos.com> writes:
Daniel Keep:
 I think Walter said something a while back to the effect that making it
 possible to statically initialise AAs isn't feasible because it requires
 setting up a complex structure on the heap.
At the moment you can't statically initialize a built-in AA in D. But with a small change in D AAs such memory may be allocated statically too, when the program starts. What's the advantage of doing this? Having quicker startup times? Bye, bearophile
Apr 15 2009
parent grauzone <none example.net> writes:
  What's the advantage of doing this? Having quicker startup times?
Syntax. Read the first post of this thread.
Apr 15 2009