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


#1

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 self.events.remove(name) {
          Some(mut events)  => {
                  for i in 0..events.len() {
                           // How to compare here ?? Box<T> with Box<T>
                           if events[i] == obj { 
                                 events.remove(i);
                           }
                  }
                 
                  events
          }
          None => return;
     }

     self.events.insert(name, events);
}

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


#2

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
}

#3

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.