TIL: statically initializing an Associative Array

matheus matheus at gmail.com
Tue May 7 01:02:04 UTC 2024


On Tuesday, 7 May 2024 at 00:10:27 UTC, Andy Valencia wrote:
> I had a set of default error messages to go with error code 
> numbers, and did something along the lines of:
>
> string[uint] error_text = [
>     400: "A message",
>     401: "A different message"
> ];
>
> and got "expression .... is not a constant"
>
> I eventually found this discussion:
>     https://issues.dlang.org/show_bug.cgi?id=6238
>
> I understand that it's problematic, but a message which makes 
> it clearer that compile-time initialization of global AA's are 
> not supported?  Because it cost me about a half hour trying to 
> figure out what I was doing wrong.
>
> (My workaround was to initialize the data structure once during 
> app startup.)

Based on what I understood and that issue, I think it was fixed:

import std.stdio;

string[uint] aa1 = [1:"ABC",2:"DEF"];

void main(){
     auto aa2 = ['A':1,'B':2];

     writeln(aa1[1]);
     writeln(aa1[2]);
     writeln(aa2['A']);
     writeln(aa2['B']);
}

Prints:

ABC
DEF
1
2

Matheus.


More information about the Digitalmars-d-learn mailing list