Is there any way to call closure behind a mut self?

Is there any way to call closure behind a mut self like following code?

struct Test<F:FnOnce()>
{
    p:F
}

impl <F:FnOnce()> Test<F>
{
    fn new(_p:F)->Test<F>
    {
        Test
        {
            p:_p
        }
    }
    fn call_closure(&mut self)
    {
        (self.p)();
    }
    fn print(&mut self)
    {
        println!("hahahah");
    }
}
fn main() {
    let inner_a = std::rc::Rc::new(std::cell::RefCell::new(Test::new(|| println!("aaaaa"))));
    let mut a = Test::new(|| inner_a.as_ref().borrow_mut().print());
    a.call_closure();
    println!("Hello, world!");
}

The problem is that call_closure(&mut self) could be called multiple times on the same a: Test<F> while the closure of type F: FnOnce() inside it can only be called once.

There’s multiple options how to proceed depending on what you want:

  • Make Test only support closures that can be called multiple times (so change both occurrences of FnOnce in your program to FnMut)
  • Make the field of Test an Option that can be set to None after the closure is first called. (For example like this.)
2 Likes

Option is a great Option! :grin: Thanks! It works!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.