I have a custom type that includes a string as it’s unique ID. I would like to simplify operations by permitting lookups of this object by just the String. I proceed with the basic construction and of course it doesn’t work by default.
julia> struct MyString
name::String
end
julia> a = MyString("Ilya")
MyString("Ilya")
julia> d = Dict{MyString,Integer}()
Dict{MyString, Integer}()
julia> d[a] = 1
1
julia> d["Ilya"]
ERROR: KeyError: key "Ilya" not found
Easy, I’ll overload equals and everything should be dandy:
julia> import Base: ==
julia> ==(x::MyString, y::String) = x.name == y
== (generic function with 225 methods)
julia> a == "Ilya"
true
julia> d["Ilya"]
ERROR: KeyError: key "Ilya" not found
Hmm, maybe I need to overload hash() as well?
julia> import Base: hash
julia> hash(mys::MyString) = hash(mys.name)
hash (generic function with 88 methods)
julia> d["Ilya"]
ERROR: KeyError: key "Ilya" not found
So I was pretty stumped at this point, but then I tried overloading ==(x::String, y::MyString) = x == y.name
and everything worked beautifully.
My question is what is the correct way to implement this behavior? Do I need to overload all three functions or can I get away with just one?