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)

Reply via email to