I'm trying to pass a particular closure to a function in an external crate that requires a &impl Fn
, and will store a reference internally.
I've gotten my problem simplified to to look like this:
use std::rc::Rc;
use std::cell::Cell;
/// stuff I can control
struct MyWrapper<'a> {
obj: Option<LibObj<'a, f64>>,
injection_closure: Box<dyn Fn(&f64) -> f64 + 'a >,
}
impl<'a> MyWrapper<'a> {
fn new(transaction: Rc<Cell<f64>>) -> MyWrapper<'a> {
// I want any way to get this closure stuffed into a LibObj
// doesn't matter if it's stored in a Box, Rc, Mutex, ...
let injection_closure = Box::new({ move |_: &f64| transaction.get() });
let mut retv = MyWrapper {
injection_closure: injection_closure,
obj: None,
};
retv.obj = Some(LibObj::new(
&*retv.injection_closure
));
retv
}
}
/// stuff I can't control
struct LibObj<'f_lifetime, Arg> {
my_thing: ThingWrapper<'f_lifetime, Arg>,
}
impl<'f_lifetime, Arg> LibObj<'f_lifetime, Arg>
{
pub fn new(f: &'f_lifetime impl Fn(&Arg) -> Arg)
-> Self
{
let thing = ThingWrapper::new(f);
LibObj { my_thing: thing }
}
}
pub struct ThingWrapper<'f_lifetime, Arg>
{
f: &'f_lifetime dyn Fn(&Arg) -> Arg,
}
impl<'f_lifetime, Arg> ThingWrapper<'f_lifetime, Arg>
{
pub fn new(f: &'f_lifetime impl Fn(&Arg) -> Arg)
-> Self
{
ThingWrapper { f }
}
}
This solution doesn't compile, giving the error error[E0277]: the size for values of type 'dyn for<'r> Fn(&'r f64) -> f64' cannot be known at compilation time
.
I understand what the error means and why it says as much, but I'm having trouble figuring out how to avoid it while still respecting the necessary lifetime constraints.
Sample code is on Rust Playground at here.