How to store different closures with the same type in a struct?


#1

How do I store different closures with the same type in this situation? Often Boxing is stated as a solution and the compiler gives that hint, too. But I can’t figure out how to do it in this situation.

struct Test<F> where F: FnMut(i32) {
    f: F,
}

impl<F> Test<F> where F: FnMut(i32) {
    fn new(f: F) -> Self {
        Test { f: f }
    }

    fn set(&mut self, f: F) { self.f = f; }
}

fn main() {
    let mut t = Test::new(|i| {});
    t.set(|i| {});
}

#2
struct Test {
    f: Box<dyn FnMut(i32)>,
}