Allowing a Trait to be Stored in a HashSet Seems...Complicated

77 points shortspider

Hi,

I'm new to rust but not programming, however the majority of my experience has been with managed OO languages (C#, Java, etc).

I am trying to store structs that implement a trait in a HashSet. Something like:

trait MyTrait {}
let set: HashSet<Box<dyn MyTrait>> = HashSet::new();

I need the underlying type so I don't want to use impl MyTrait as the HashSet type.

I tried the above initially but the compiler complained that MyTrait needed to implement Eq, PartialEq, Hash, and Clone which makes sense. However implementing them was very tricky for me to figure out. I ended up following the examples laid out here and here.

Everything now works but my question is why is this so complicated? What does this complexity gain? Or have I over complicated this somehow? Should I not be doing this? This is why I mentioned my previous experience, I may be trying to apply a methodology that isn't well suited for rust. What I have just feels overly complicated and usually when I've done something complicated it will eventually come back to bite me.

Thanks in advance and sorry if this is a silly question.

​