www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - foreach AA key char[] type change

reply bearophile <bearophileHUGS lycos.com> writes:
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
Jun 05 2010
parent reply "Steven Schveighoffer" <schveiguy yahoo.com> writes:
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
Jun 05 2010
next sibling parent bearophile <bearophileHUGS lycos.com> writes:
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
Jun 06 2010
prev sibling parent bearophile <bearophileHUGS lycos.com> writes:
http://d.puremagic.com/issues/show_bug.cgi?id=4279
http://d.puremagic.com/issues/show_bug.cgi?id=4281
Jun 06 2010