Assoc array init

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Feb 4 08:20:06 UTC 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





More information about the Digitalmars-d-learn mailing list