This playground project has a simplified version of the code I'm trying to compile.
use std::sync::{Arc, Mutex, MutexGuard};
pub trait Runnable {
fn run(&mut self) -> Option<String>;
}
pub struct Value {}
impl Runnable for Value {
fn run(&mut self) -> Option<String> {
Some("Value".to_string())
}
}
pub struct RunList {
runnables: Vec<Arc<Mutex<Runnable>>>,
}
impl RunList {
pub fn run<R>(&mut self, index: usize, mut runner: R)
where
R: FnMut(&mut MutexGuard<Runnable>),
{
let runnable_arc = self.runnables[index].clone();
let mut runnable = runnable_arc.lock().unwrap();
runner(&mut runnable);
}
}
fn main() {
let mut runnables = Vec::<Arc<Mutex<Runnable>>>::with_capacity(1);
runnables.push(Arc::new(Mutex::new(Value {})));
let mut run_list = RunList { runnables };
run_list.run(0, |runnable| {
println!("Hello, {}", runnable.run().unwrap());
});
}
I want a vector of trait objects, where each object is protected by an Arc
and a Mutex
, and then to be able to call a trait method on each object.
I have a "borrowed value does not live long enough" error but I can't see the difference from this question/answer.
error[E0597]: `runnable_arc` does not live long enough
--> src/main.rs:25:28
|
25 | let mut runnable = runnable_arc.lock().unwrap();
| ^^^^^^^^^^^^ borrowed value does not live long enough
26 | runner(&mut runnable);
27 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...