Hello there,
I'm trying to move a trait function (Handler::some_fn in the example below) into a separate closure that just wraps the trait function (see Y::bind in example below).
Here is my example code:
use std::rc::Rc;
struct Service;
trait Handler {
fn some_fn(&self, x: i32);
}
impl Handler for Service {
fn some_fn(&self, x: i32) {
}
}
struct Y {
some_fn: Box<dyn Fn(i32)>,
}
impl Y {
fn bind<T: Handler>(&mut self, handler: &Rc<T>) {
let s1 = Rc::clone(&handler);
self.some_fn = Box::new(
move |x: i32| {
s1.some_fn(x);
}
);
}
}
Since I'm using an explicit Rc::clone
I would have expected this could be moved into the closure. However I'm getting the following error:
error[E0310]: the parameter type `T` may not live long enough
--> src/main.rs:21:24
|
21 | self.some_fn = Box::new(
| ________________________^
22 | | move |x: i32| {
23 | | s1.some_fn(x);
24 | | }
25 | | );
| |_________^ ...so that the type `T` will meet its required lifetime bounds
|
help: consider adding an explicit lifetime bound...
|
19 | fn bind<T: Handler + 'static>(&mut self, handler: &Rc<T>) {
| +++++++++
I don't understand why I need a lifetime, since I would have expected Rc to take care of exactly that. How would I specify a matching lifetime?