Why Does Dscanner Warn About a Missing toHash if opEquals is Defined?

BLM768 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jul 31 10:48:48 PDT 2016


On Sunday, 31 July 2016 at 16:39:59 UTC, Jack Stouffer wrote:
> But D provides a default toHash for every type if it's not 
> defined. I was wondering why not just rely on that version.

If two objects are equal, their hashes must also be equal. 
Consider this example:

struct Nullable(T) {
   bool isNull;
   T value;

   bool opEquals(Nullable!T other) {
     if(this.isNull != other.isNull) return false;
     // Any two nulls are equal.
     if(isNull) return true;
     return this.value == other.value;
   }
}

auto n1 = Nullable!int(true, 3);
auto n2 = Nullable!int(true, 4);

writeln(n1 == n2); // true
writeln(n1.hashOf == n2.hashOf); // false = BAD!

Now that I think about it, maybe this should be in the language 
docs; I don't think they mention it. 
(https://dlang.org/spec/operatoroverloading.html#equals)


More information about the Digitalmars-d-learn mailing list