I’ve got a struct, one of whose fields is a function whose type is not known at compile time. In trying to get this to work, I’ve done:
struct Foo<T> {
init: Box<Fn() -> T>,
}
However, I’m having trouble getting the lifetimes to work. I have the following implementation that involves two different constructors which each initialize init
differently:
trait Initializable {
fn init() -> Self;
}
struct Foo<T> {
init: Box<Fn() -> T>,
}
impl<T> Foo<T> {
fn new<F: Fn() -> T>(init: F) -> Foo<T> {
Foo { init: Box::new(init) }
}
}
impl<T: Initializable> Foo<T> {
fn new_initializable() -> Foo<T> {
Foo { init: Box::new(T::init) }
}
}
However, I get a compiler error relating to lifetimes (I won’t paste it here because it’s long and verbose, but you can see it by trying to compile the source here).
Does anyone know a way around this? I’ve gone down the rabbit hole of trying to annotate different types or functions with lifetimes, and haven’t managed to get it to work. Thanks!