www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Associative array literal. Why doesn't it compile?

reply "Adel Mamin" <adel mm.st> writes:
Compiler dmd_2.068.0-0_amd64.deb on Ubuntu 12.04 Linux:

auto lookup = [ "one":1, "two":2 ];

The dmd error:
Error: non-constant expression ["one":1, "two":2]

Why doesn't it compile?
As a workaround I could do the assignment one element at a time 
in a loop. It would be uglier though.
Aug 13 2015
next sibling parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 08/13/2015 11:48 PM, Adel Mamin wrote:
 Compiler dmd_2.068.0-0_amd64.deb on Ubuntu 12.04 Linux:

 auto lookup = [ "one":1, "two":2 ];

 The dmd error:
 Error: non-constant expression ["one":1, "two":2]
I think the problem is when the variable is defined at module scope. It works inside functions, etc.
 Why doesn't it compile?
 As a workaround I could do the assignment one element at a time in a
 loop. It would be uglier though.
A better workaround is to initialize it in the module constructor: immutable int[string] lookup; shared static this() { lookup = [ "one":1, "two":2 ]; } void main() { assert("one" in lookup); } Ali
Aug 13 2015
prev sibling parent reply "BBasile" <bb.temp gmx.com> writes:
On Friday, 14 August 2015 at 06:48:27 UTC, Adel Mamin wrote:
 Compiler dmd_2.068.0-0_amd64.deb on Ubuntu 12.04 Linux:

 auto lookup = [ "one":1, "two":2 ];

 The dmd error:
 Error: non-constant expression ["one":1, "two":2]

 Why doesn't it compile?
 As a workaround I could do the assignment one element at a time 
 in a loop. It would be uglier though.
It's because of the key type (string is a library type). You have to initialize it by hand. Explanation here: http://stackoverflow.com/a/26862994/3661500 see the comment of Adam D. Ruppe. Although this case was 'a bit' different since the AA had to be immutable (in this case it was only possible to initialize it in a static module constructor or in class/struct constructor). But it's almost the same problem.
Aug 14 2015
parent reply "anonymous" <anonymous example.com> writes:
On Friday, 14 August 2015 at 07:04:53 UTC, BBasile wrote:
 It's because of the key type (string is a library type).
This is not true. It's not because of the key type. And string is not a library type.
Aug 14 2015
parent "Temtaime" <temtaime gmail.com> writes:
It's because it's implemented in DMD only partly.
There's a bug report associated with it.
Aug 14 2015