Different structs with the same properties

I have two .jld2 files.
I loaded structs from the above files, which have the same properties but they are regarded as different objects as follows:

julia> for prop in [fieldnames(typeof(a))..., fieldnames(typeof(b))...,]
       if getproperty(a, prop) != getproperty(b, prop)
       error()
       end
       end

julia> a == b
false

I tried to reproduce the above phenomenon with a minimum example but it behaves in a different way like this:

julia> struct MyStruct
       a
       b
       end

julia> mine1 = MyStruct(1, 2)
MyStruct(1, 2)

julia> mine2 = MyStruct(1, 2)
MyStruct(1, 2)

julia> mine1 == mine2
true

I don’t get it so far.
Anyone can explain this…?

I think it is because the default implementation of == for a new struct falls back on ===, which tests if the two objects share the same memory address (i.e. if they are one and the same). If your struct includes mutable fields, you need to redefine Base.:(==) for your own struct in a way that compares field values instead.

3 Likes

Yeah that’s right. Here’s an example with the same struct MyStruct but now containing a mutable object (a Vector)

julia> mine1 = MyStruct([1, 2], 1);

julia> mine2 = MyStruct([1, 2], 1);

julia> mine1 == mine2
false

and you can see that equality fails.

@iHany you might find the package AutoHashEquals.jl useful

2 Likes

Thank you guys!!
This helped me a lot in understanding the mechanism and why it happened.

2 Likes