Cannot move field of FnOnce

Hi, I'm beginner to rust. Can any one explain why this snippet doesn't work? and what's the best practice to do the same thing?
struct Foo where F: FnOnce() {
f: F,
}

impl<T> Foo<T> where T: FnOnce() {
    fn new(f: T) -> Self {
        Foo {
            f
        }
    }
}

impl<F> Drop for Foo<F> where F: FnOnce() {
    fn drop(&mut self) {
        let y = self.f;  //error: cannot move
        y();
    }
}

The problem here is that self.f will be dropped after the Drop::drop function is run when dropping. You can wrap f in an Option and then use self.f.take().unwrap() in the Drop impl. Option::take replaces the option with a None and returns the old value.

2 Likes

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.