Why does `==` for custom types not compare field equality by default

Hi everyone,

so this is less of a question how this works, but more of why it is implemented that way (I am trying to get into the Julia way of thinking and sometimes language designs seem counter intuitive).

So I know that == falls back to === so if I don’t overload == for my own type only truly identical objects (in the sense of ===) are treated as equal.
Intuitively I would expect == to return true if it returns true for each field.
So the following behaviour seems weird to me:

struct X
x
end

julia> X([1]) == X([1])
false

I personally would expect the behaviour of X to follow the behaviour of its field, i.e.

julia> [1] == [1]
true

julia> [1] === [1]
false

So now I find myself going through my code and implementing this exact behaviour for all my types which is a bit tedious.
Why would anyone want this? Could anyone give me an example where my suggested default behaviour is not wanted?
Or I guess somewhere there might already be a discussion about this and I was just too stupid to find it. So I would also be grateful if someone could point me in the direction of the appropriate Git issue.

4 Likes

Not an answer, but if your types contain a lot of containers, you can try StaticArrays.jl. Immutable types do not differ in how they are compared by == or ===.

I don’t have an answer of your original question (“Why is it implemented like this?”). But you may consider using AutoHashEquals.jl to simplify the process of adapting it to your desired form.

2 Likes

Here’s the discussion: == for immutables should recursively call == on its fields · Issue #4648 · JuliaLang/julia · GitHub

5 Likes

Thanks, that is a great suggestion!

Thank you very much,

this discussion partly goes over my head, but I see that it is a controversial topic. So let’s see whether there will be changes for 2.0