Create a user-type set

hellow, how to create a user type set?

# i do
mutable struct UserType
    id::Int
end
Base.:(==)(a::UserType, b::UserType) = a.id == b.id
set = Set((UserType(1), UserType(2),))
UserType(1) == UserType(1)  # -> true
# but i have
push!(set, UserType(1))  # -> Set{UserType} with 3 elements

You need to implement hash as well as a Set is based on a Dict. See about hashing here Performance issues when working with dict - #4 by mauro3

1 Like

The AuthHashEquals.jl README has this warning… probably not a good idea to use mutable objects in a Set (or as keys in a Dict).

If you use this macro for a mutable type, then the hash depends on the contents of that type, so changing the contents changes the hash. Such types should not be stored in a hash table (Dict) and then mutated, because the objects will be “lost” (as the hash table assumes that hash is constant).

1 Like