www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Assoc array init

reply JN <666total wp.pl> writes:
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.
Feb 03 2020
next sibling parent Boris Carvajal <boris2.9 gmail.com> writes:
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
Feb 04 2020
prev sibling parent Jonathan M Davis <newsgroup.d jmdavisprog.com> writes:
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
Feb 04 2020