Hi there!
I'm currently struggling with the lifetime of function pointers. Here is my (simplified) code (link to the playground):
use std::any::Any;
#[derive(Clone, Copy)]
enum A<T: 'static> {
VA(fn(T) -> bool)
}
enum B<T: 'static> {
VA(Box<dyn Fn(T) -> Box<dyn Any>>)
}
impl<T: 'static> From<A<T>> for B<T> {
fn from(a: A<T>) -> B<T> {
match a {
A::VA(func) => B::VA(Box::new(|val| Box::new(func(val))))
}
}
}
This code fails to compile with the following error :
error[E0597]: `func` does not live long enough
--> src/lib.rs:15:58
|
15 | A::VA(func) => B::VA(Box::new(|val| Box::new(func(val))))
| ------------------------^^^^-------
| | | |
| | | borrowed value does not live long enough
| | value captured here
| cast requires that `func` is borrowed for `'static`
16 | }
17 | }
| - `func` dropped here while still borrowed
error: aborting due to previous error
I don't understand why I get this error. Aren't function pointers supposed to have the 'static
lifetime? I also tried to .clone()
the pointer in the match
arm, so I can but sure I get an fn(T) -> bool
and not a reference to it, but that didn't change anything.
Any idea?
Thanks in advance for your help