On Thursday, 6 April 2023 at 01:53:31 UTC, John Xu wrote:
> I saw on doc:
https://dlang.org/spec/hash-map.html#static_initialization,
that map/dict/associative array, still can't be initialized like below:
NOTE: Not yet implemented.
immutable long[string] aa = [
"foo": 5,
"bar": 10,
"baz": 2000
];
I'm wondering when this is be ready? Python can write this way long time ago.
Specifically, what doesn't work is initializing an associative array at compile time. You can use this syntax to initialize an AA at runtime, and it will work just fine.
For example:
// Error - global variables are initialized at compile time
long[string] globalAa = ["foo": 5, "bar": 10];
void main()
{
// No error - local variables are initialized at runtime
long[string] localAa = ["baz": 2000, "quux": 9999];
}
To work around this limitation, you can initialize a global AA using a static module constructor. For example:
long[string] globalAa;
static this()
{
globalAa = ["foo": 5, "bar": 10];
}
This will perform the initialization at runtime, during program startup (before calling main
).