I have a struct that contain some methods that I'd like to call by itself later.
Is it possible to define a closure that captures self
, then I can call its methods later when I want?
struct JobFn {
pub fc: Box<dyn Fn()>,
}
struct Device {
jobs: Vec<JobFn>,
val: u8,
}
impl Device {
fn add_job_a(&mut self) {
let new_job = JobFn {
fc: Box::new(|| {
// TODO how to get self.task_a inside
}),
};
self.jobs.push(new_job);
}
fn task_a(&mut self) {
println!("this is a,{:?}", self.val);
self.val = 100;
}
fn exec(&mut self) {
for i in 0..self.jobs.len() {
let f = self.jobs[i].fc.as_mut();
f();
}
}
}