The problem is not that function pointers in general are not clonable, but that you actually have a function that is generic over the lifetime of the &str
. For example if you replace the &str
with i32
your code will compile, because i32
has no lifetimes. In your situation you need to make the lifetimes on the function pointer explicit:
type TypeFn<'a> = fn(s: &'a str);
This obviously bubbles up to the struct, too:
#[derive(Clone)]
struct MyStruct<'a> {
field: TypeFn<'a>
}
This prevents the following kind of code:
let my_var = MyStruct{field: my_fn};
let s = String::new();
(my_var.field)(&s);
Actually the problem is that it's a bug. As shown in @MattBrubeck 's answer Function pointers implement Copy
. So you can just implement Clone
manually by using the function pointer's Copy
impl:
impl Clone for MyStruct {
fn clone(&self) -> Self {
MyStruct {
field: self.field,
}
}
}