I've found two ways to return closures from functions that use enclosing state:
fn closure_try(t: u64) -> Box<dyn Fn(u64) -> u64> {
let f = |x: u64| x + t;
return Box::new(f);
}
fn closure_try2(t: u64) -> impl Fn(u64) -> u64 {
let f = move |x: u64| x + t.clone();
return f;
}
Now, I need to store the output object into a struct and also be able to clone it.
Unfortunately, in the second instance, trait impl
objects cannot be in struct position.
struct A {
b: impl Fn(u64) -> u64
}
This fails with: impl Trait
not allowed outside of function and method return types.
In the first example, the boxed dynamic trait object cannot be copied or cloned.
fn duplicate(f: Box<dyn Fn(u64) -> u64>) -> Box<dyn Fn(u64) -> u64> {
f.clone()
}
This fails with the error "doesn't satisfy dyn Fn(u64) -> u64: Clone
"
What would be an idiomatic way to create a store of closures where:
- Closures can be duplicated
- Each closure can capture some enclosing state
One option I'm considering is to have these functions return a closure that return the closure, but this seems problematic.