Thread overview
Assoc array init
Feb 04, 2020
JN
Feb 04, 2020
Boris Carvajal
Feb 04, 2020
Jonathan M Davis
February 04, 2020
int[int] a = [5: 7];

void main()
{
}


This fails because apparently [5: 7] is a "non-const expression". How? Why?

Yes, I know I can just init in a static this() section, but that feels like a bad workaround.
February 04, 2020
On Tuesday, 4 February 2020 at 07:52:05 UTC, JN wrote:
> int[int] a = [5: 7];
>
> void main()
> {
> }
>
>
> This fails because apparently [5: 7] is a "non-const expression". How? Why?
>
> Yes, I know I can just init in a static this() section, but that feels like a bad workaround.

AFAIK is not implemented.
https://dlang.org/spec/hash-map.html#static_initialization
February 04, 2020
On Tuesday, February 4, 2020 12:52:05 AM MST JN via Digitalmars-d-learn wrote:
> int[int] a = [5: 7];
>
> void main()
> {
> }
>
>
> This fails because apparently [5: 7] is a "non-const expression". How? Why?
>
> Yes, I know I can just init in a static this() section, but that
> feels like a bad workaround.

It's a limitation of CTFE. A variable at module scope which is directly initialized must have its value known at compile-time, and while AAs can be _used_ at compile-time, the compiler cannot currently transfer those AAs to runtime. That may or may not be fixed in the future (e.g. originally, it wasn't possible to have class objects transfer from compile-time to runtime, but at some point, that was fixed). Either way, for now, it means that if you want to initialize an AA like the one here, you will need to use a static constructor.

- Jonathan M Davis