# Hashing of different types with same contents

**URL:** https://discourse.julialang.org/t/hashing-of-different-types-with-same-contents/54839
**Category:** General Usage
**Created:** [February 8, 2021, 12:50pm UTC](https://discourse.julialang.org/t/hashing-of-different-types-with-same-contents/54839 "2021-02-08T12:50:41Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![jagot](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jagot/32/12217_2.png) [@jagot](https://discourse.julialang.org/u/jagot)
#### Post date: [February 8, 2021, 12:50pm UTC](https://discourse.julialang.org/t/hashing-of-different-types-with-same-contents/54839/1 "2021-02-08T12:50:41Z")

</div>

Say I have two types with `hash` implementations defined like this

```julia
struct A{T}
  t::T
end
Base.hash(a::A, h::UInt) = hash(a.t, h)

struct B{T}
  t::T
end
Base.hash(b::B, h::UInt) = hash(b.t, h)

```

I will get their hashes to agree:

```julia
julia> hash(A(1)) == hash(B(1))
true

```

How do I _avoid_ this? I.e. I would like their hashes to not agree. One way would be to mix in “magical numbers”, like so:

```julia
Base.hash(a::A, h::UInt) = hash(a.t, hash(0xa, h))
Base.hash(b::B, h::UInt) = hash(b.t, hash(0xb, h))

```

which yields

```julia
julia> hash(A(1)) == hash(B(1))
false

```

Is this the preferred way?

---

<div class="post-metadata">

### Author: ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)
#### Post date: [February 8, 2021, 1:11pm UTC](https://discourse.julialang.org/t/hashing-of-different-types-with-same-contents/54839/2 "2021-02-08T13:11:44Z")

</div>

> [@jagot](#):
>
> Is this the preferred way?

I think the preferred way is to mix in the hash of the type itself, e.g. `hash(a.t, hash(A, h))`. But if you have code that relies on the hash being different then you are likely to have a bug since hash collisions are possible.

---

<div class="post-metadata">

### Author: ![jagot](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jagot/32/12217_2.png) [@jagot](https://discourse.julialang.org/u/jagot)
#### Post date: [February 8, 2021, 1:23pm UTC](https://discourse.julialang.org/t/hashing-of-different-types-with-same-contents/54839/3 "2021-02-08T13:23:47Z")

</div>

For sure, I’m just using it as a poor man’s checksum; I dump calculations to file with a filename that depends on the basis set employed, and have no problem that the calculation has to be redone when the hash value changes (i.e. new Julia versions). I just needed to also be able to disambiguate between different basis set types, and not just their locations.
