# Hash function for immutable struct containing mutable vectors

**URL:** <https://discourse.julialang.org/t/hash-function-for-immutable-struct-containing-mutable-vectors/68326>\
**Category:** General Usage\
**Tags:** mutable-structure, hash\
**Created:** [September 17, 2021, 11:05am UTC](https://discourse.julialang.org/t/hash-function-for-immutable-struct-containing-mutable-vectors/68326 "2021-09-17T11:05:03Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![greatpet](https://avatars.discourse-cdn.com/v4/letter/g/e495f1/32.png) [@greatpet](https://discourse.julialang.org/u/greatpet)\
**Post date:** [September 17, 2021, 11:05am UTC](https://discourse.julialang.org/t/hash-function-for-immutable-struct-containing-mutable-vectors/68326/1 "2021-09-17T11:05:03Z")

</div>

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

```julia
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?

---

<div class="post-metadata">

**Author:** ![raminammour](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/raminammour/32/13572_2.png) [@raminammour](https://discourse.julialang.org/u/raminammour)\
**Post date:** [September 17, 2021, 6:04pm UTC](https://discourse.julialang.org/t/hash-function-for-immutable-struct-containing-mutable-vectors/68326/2 "2021-09-17T18:04:30Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Mason](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mason/32/2423_2.png) [@Mason](https://discourse.julialang.org/u/Mason)\
**Post date:** [September 17, 2021, 6:24pm UTC](https://discourse.julialang.org/t/hash-function-for-immutable-struct-containing-mutable-vectors/68326/3 "2021-09-17T18:24:45Z")

</div>

This is quite easy to check:

```julia
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](https://github.com/andrewcooke/AutoHashEquals.jl) which automates different equality and hash definitions for you

```julia
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

```
