0

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();
        }
    }
}
E_net4
  • 27,810
  • 13
  • 101
  • 139
lamGuo
  • 1
  • This would be a circular reference, which is not possible as is. It might be, with `Rc` and `RefCell`, but I want to ask: what for? You can just pass `self` when invoking `f` in `exec`, no need to capture. – Caesar Jan 18 '23 at 08:48
  • As Caesar already mentioned this would be a case of: [Why can't I store a value and a reference to that value in the same struct?](https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct) – cafce25 Jan 18 '23 at 09:01

0 Answers0