Struct hash issues with string fields
Jonathan M Davis
jmdavisProg at gmx.com
Sat May 26 15:01:52 PDT 2012
On Saturday, May 26, 2012 21:53:07 Andrej Mitrovic wrote:
> I don't understand this:
>
> import std.stdio;
>
> struct Symbol { string val; }
>
> void main()
> {
> int[string] hash1;
> hash1["1".idup] = 1;
> hash1["1".idup] = 2;
> writeln(hash1); // writes "["1":2]"
>
> int[Symbol] hash2;
> Symbol sym1 = Symbol("1".idup);
> Symbol sym2 = Symbol("1".idup);
> hash2[sym1] = 1;
> hash2[sym2] = 1;
> writeln(hash2); // writes "[Symbol("1"):1, Symbol("1"):1]"
> }
>
> Why are sym1 and sym2 unique keys in hash2? Because the hash
> implementation checks the array pointer instead of its contents? But
> then why does hash1 not have the same issue?
>
> I can't override toHash() in a struct, so what am I supposed to do in
> order to make "sym1" and "sym2" be stored into the same hash key?
Why can't you have a toHash in your struct? Your struct should be able to have
a toHash just like it can have a toString. If anything, I find it disturbing
that the code compiles _without_ a definition for opHash in the struct.
Now, that aside, the results with hash2 definitely look like a bug to me. It's
probably just the result of one more of the many issues with the current AA
implementation.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list