Thread overview
foreach AA key char[] type change
Jun 06, 2010
bearophile
Jun 06, 2010
bearophile
Jun 06, 2010
bearophile
June 06, 2010
Do you know why this D2 program prints  const(char)[]  instead of  char[] ?

import std.stdio: writeln;
void main() {
    int[char[]] data = [cast(char[])"foo" : 1];
    foreach (key, val; data)
        writeln(typeid(typeof(key)));
}

Bye and thank you,
bearophile
June 06, 2010
On Sat, 05 Jun 2010 20:42:43 -0400, bearophile <bearophileHUGS@lycos.com> wrote:

> Do you know why this D2 program prints  const(char)[]  instead of  char[] ?
>
> import std.stdio: writeln;
> void main() {
>     int[char[]] data = [cast(char[])"foo" : 1];
>     foreach (key, val; data)
>         writeln(typeid(typeof(key)));
> }

Probably because you aren't allowed to change keys for AAs.  Passing the key as a char[] type would allow that.

Although I wasn't aware the compiler did that...

-Steve
June 06, 2010
Steven Schveighoffer:
> Probably because you aren't allowed to change keys for AAs.  Passing the key as a char[] type would allow that.

Modifying AA keys after they are inserted in the AA is bad because their hash value and position inside the AA doesn't get recomputed.

The current design/behaviour is surprising and bad, because I have asked for a key type and the runtime/compiler gives me a different key type (forcing me to use casts). There are two possible behaviours that I can accept here:

1) to disallow AAs with mutable keys, their literals and definition too (as Python does);
2) or to allow mutable keys (and hope the programmer will not mutate them) (as I think D1 does).

Thank you for your answer,
bye,
bearophile
June 06, 2010
http://d.puremagic.com/issues/show_bug.cgi?id=4279 http://d.puremagic.com/issues/show_bug.cgi?id=4281