How to iterate over array of boxed trait objects


#1

Consider the following problem. I have an array of boxed trait objects. I need to iterate over this array and for each element call a function that accepts a reference to the trait object. The code looks like this:

trait Handler {
    fn onEvent(&self);
}

struct Handler1;
struct Handler2;

impl Handler for Handler1 {
    fn onEvent(&self) {
        println!("Handler1: onEvent");        
    }
}

impl Handler for Handler2 {
    fn onEvent(&self) {
        println!("Handler2: onEvent");        
    }
}

fn handleEvent(handler: &Handler) {
    handler.onEvent();
}

fn main() {
    let handlers: [Box<Handler>; 2] = [Box::new(Handler1), Box::new(Handler2)];

    for handler in handlers.iter() {
        // doesn't work
        // handleEvent(&*handler);
    }
}    

In the above code the commented code to call handleEvent function doesn’t compile with
error: the trait Handler is not implemented for the type Box<Handler> [E0277]

I understand that handler in the for loop has type &Box<Handler> so what I should do is somehow convert &Box<Handler> to &Handler. Any ideas how to do that?

Thanks,
Dmitry


#2

Yes, &**handler does work. You’re getting a &Box<Handler> from the iterator, so you need to deref it twice.