Associative Array - where's my error?

Jesse Phillips jessekphillips+D at gmail.com
Wed Apr 27 22:11:04 PDT 2011


Adrian Mercieca Wrote:

> Hi,
> 
> I am currently learning D, but have ran into a problem.
> 
> I wrote this simple program:
> 
> import std.stdio;
> import std.string;
> import std.conv;
> 
> void main()
> {
> 	int[string] dataMap;
> 	
> 	foreach(line; stdin.byLine() ) {
> 		auto s = line.split("\t");
> 		auto anum = to!int(s[0]);
> 		auto aname = cast(string)s[1];
> 		dataMap[aname] = anum;
> 	}
> 	
> 	foreach(s; dataMap.keys.sort) {
> 		writeln(s);
> 	}
> }
> 

Quite simple your error is in using cast(string). Solution use to!string(s[1])

The explanation:

byLine reuses the buffer as it iterates, this is why you see YZ, though I would expect remains of some other words in there. Associative Array keys must be immutable (so that their value is not changed by another reference). By casting to string you have told the type system "This value cannot be changed by me or any other reference to this data." But in reality you do continue to modify it because byLine still has the reference.

Casting types is making statements about the type, it is not converting the type (in general). You must have inserted the cast because the compiler said s[1] wasn't immutable and figured you could "force it" into being so. In such cases the compiler is telling something is wrong and you are saying "I don't care. I know I'm right." Don't use cast, to!() is much safer.

Also you could use s[1].idup instead of cast or to!().


More information about the Digitalmars-d-learn mailing list