Reputation: 5093
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
.
Upvotes: 4
Views: 373
Reputation: 5093
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
Upvotes: 5