Hash function for immutable struct containing mutable vectors

Suppose I have an immutable struct A containing immutable fields as well as a (mutable) vector of immutable objects (such as Int64 objects),

struct A
    x::Int
    y::Vector{Int}
end

Does Julia automatically define sensible hash and isequal functions for objects of my type A, taking into account the content (not the memory address) of the vector?

See the help for ?== and ?isequal and ?hash. For new types you need to implement equality checks, and hash. Base implements the fallback ==(a,b) = a===b so falls back to egal.

This is quite easy to check:

julia> struct A
           x::Int
           y::Vector{Int}
       end

julia> A(1, [1, 2]) == A(1, [1, 2])
false

It’s up to you whether you think this is sensible or not. People disagree.

If this is not the behaviour you want, there’s a package AutoHashEquals.jl which automates different equality and hash definitions for you

julia> using AutoHashEquals

julia> @auto_hash_equals struct A
           x::Int
           y::Vector{Int}
       end

julia> A(1, [1, 2]) == A(1, [1, 2])
true
1 Like