Associative arrays give compile error

Denis Koroskin 2korden at gmail.com
Tue Oct 5 04:13:13 PDT 2010


On Tue, 05 Oct 2010 15:08:39 +0400, Bob Cowdery <bob at bobcowdery.plus.com>  
wrote:

>  On 05/10/2010 12:04, Denis Koroskin wrote:
>> On Tue, 05 Oct 2010 14:57:22 +0400, Bob Cowdery
>> <bob at bobcowdery.plus.com> wrote:
>>
>>>  On 05/10/2010 11:45, Denis Koroskin wrote:
>>>> On Tue, 05 Oct 2010 14:23:47 +0400, Bob Cowdery
>>>> <bob at bobcowdery.plus.com> wrote:
>>>>
>>>>>  I can't seem to get any sense out of associative arrays. Even the
>>>>> simplest definition won't compile so I must be doing something daft.
>>>>>
>>>>> int[string] aa = ["hello":42];
>>>>>
>>>>> Error: non-constant expression ["hello":42]
>>>>>
>>>>> What exactly is not constant about this. The example is straight
>>>>> out the
>>>>> book. Using D 2.0.
>>>>>
>>>>> bob
>>>>
>>>> What exactly compiler version are you using (run dmd with no args)?
>>>> Works perfectly fine here (dmd2.049).
>>>
>>> It says 2.049. How odd. I've got a fair amount of code and everything
>>> else compiles fine.
>>
>> Can you please post complete code snippet that fails to compile?
>>
>> Here is the code I used to test:
>>
>> module aa;
>>
>> import std.stdio;
>>
>> void main()
>> {
>>     int[string] aa = ["hello":42];
>>     writeln(aa["hello"]);
>> }
>>
>> # dmd -run aa.d
>
> Ah! It's some other code below it that is not giving an error but
> causing the error above. So the compiler is getting confused. What I was
> actually trying to do was create an associative array with a string as a
> key and a Tuple as the value. Now
>
> auto aa = [
>     "some string": (100.0, 6100.0)
> ]
>
> compiles but is clearly wrong and gives rise to other errors.  Does
> anyone know the correct way to define this and then access the tuple.

import std.stdio;
import std.typecons;

void main()
{
	auto aa = ["hello": tuple(100.0, 6100.0)];
	auto result = aa["hello"];
	
	writeln(result.field[0], " ", result._1); // primary and alternative way
}


More information about the Digitalmars-d-learn mailing list