Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a struct as a key in a Dict in Julia?

Tags:

julia

How do I use a struct as a key in a Dict? When I have a struct that contains a Matrix, I get duplicate keys in my Dict.

Here's a minimal example:

struct Test
  b::Matrix
end

a = Dict()
a[Test(fill(0, (2, 2)))] = 1
a[Test(fill(0, (2, 2)))] = 2

Results in:

Dict{Any, Any} with 2 entries:
  Test([0 0; 0 0]) => 2
  Test([0 0; 0 0]) => 1

As you can see, I have two identical-looking keys. I also tried overriding == and isequal.

like image 919
GLee Avatar asked Oct 30 '25 19:10

GLee


1 Answers

You need to override both isequal and hash. For example:

import Base.isequal, Base.hash
function isequal(t1::Test, t2::Test)
  return t1.b == t2.b
end

function hash(t::Test)
  return hash(t.b)
end
like image 52
GLee Avatar answered Nov 02 '25 13:11

GLee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!