How to compare Box<T> to check if their pointing to the same object?


I have some part in project where I need to remove element from BTreeMap<String, Vec<Box<T>>>.
it is something like this

// Somewhere in struct
events: BTreeMap<String, Vec<Box<Event>>>
fn rm(&mut self, name: String, obj: Box<Event>) {
     let events =  match {
          Some(mut events)  => {
                  for i in {
                           // How to compare here ?? Box<T> with Box<T>
                           if events[i] == obj { 
          None => return;
     }, events);

I’ve tried with as_ref(), just to get “pointer”, but it seems I can’t compare object using pointers.


Something like this should work:

fn eq<T: ?Sized>(left: &Box<T>, right: &Box<T>) -> bool {
    let left : *const T = left.as_ref();
    let right : *const T = right.as_ref();
    left == right


The comparison described by @fweimer should work, although note that in your function it’ll always be false! You take the obj by value, and Box is always a unique pointer. So obj will never point to anything inside the hashmap. It could compare to true though if you take the obj by reference (&Box<Event>), but this is kind of useless too – if you somehow obtain a reference to the box inside the hashmap, the hashmap will be considered borrowed and you won’t even be able to call the rm method.

So it seems that in your case you need an Rc pointer instead of the Box – that’ll allow you to indeed have two references to the same Event.