How do I obtain the default hash of a user-defined struct

bearophile bearophileHUGS at lycos.com
Thu Apr 3 14:42:16 PDT 2014


dnspies:

> This doesn't work.  It prints two different hashes for equal 
> objects.  I meant how do I get the default hash which is used 
> by an associative array.
>
> import std.stdio;
>
> struct my_struct {
> 	int[] arr;
> }
>
> void main() {
> 	my_struct s1;
> 	s1.arr = [1,2,3];
> 	my_struct s2;
> 	s2.arr = [1,2,3];
> 	writeln(s1 == s2);
> 	writeln(typeid(my_struct).getHash(&s1));
> 	writeln(typeid(my_struct).getHash(&s2));
> }
>
> true
> 626617119
> 2124658624

Take a look at the output of this program:

import std.stdio;

struct MyStruct {
      int[] arr;
}

void main() {
      MyStruct s1;
      s1.arr = [1,2,3];
      MyStruct s2;
      s2.arr = [1,2,3];
      writeln(s1 == s2);
      writeln(typeid(MyStruct).getHash(&s1));
      writeln(typeid(MyStruct).getHash(&s2));

      int[MyStruct] aa;
      aa[s1] = 10;
      aa[s2] = 20;
      writeln(aa);
}


I have filed this big problem four years ago or more.

Workarounds: define (carefully!) the three hash protocol methods, 
or use a tuple.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list