Initialization of associative arrays

Derek Parnell derek at psych.ward
Fri Jun 23 07:28:02 PDT 2006


On Fri, 23 Jun 2006 23:19:53 +1000, alxdef <alxdef_member at pathlink.com>  
wrote:

> How to initialize associative array like this:
>
> const some_type [char[]] arr = ... ?
>

D does not yet support compile-time initialization of associative arrays.  
Such arrays need to be initialized at run time, most usually in the module  
constructor ...

--- sample -----------
import std.stdio;
const int red = 45;
const int orange = 71;
const int yellow = 13;
const int blue = 92;
const int green = 88;

const int [char[]] arr;

static this()
{
     arr["apple"] = red;
     arr["orange"] = orange;
     arr["banana"] = yellow;
     arr["berry"] = blue;
}

void main()
{
     foreach(char[] k, int c; arr)
         writefln("%s is %s", k, c);

}
--------------------

Note that you can still have a 'const' associative array even though it is  
initialized at run time because such an array can *only* be initialized in  
the module constructor.

-- 
Derek Parnell
Melbourne, Australia



More information about the Digitalmars-d mailing list