How to clone a function pointer

I have a structure with a field that is a pointer to a function. I want to implement the Clone trait for this structure, but I cannot, because pointers to objects cannot be cloned if they have at least one parameter:

 fn my_fn(s: &str) { println!("in my_fn {}", s); } type TypeFn = fn(s: &str); #[derive(Clone)] struct MyStruct { field: TypeFn } fn main() { let my_var = MyStruct{field: my_fn}; let _ = my_var.clone(); } 

Link to the playground .

+6
source share
2 answers

The problem is not that function pointers are not cloned at all, but you actually have a function that is common over the lifetime &str . For example, if you replace &str with i32 , your code will compile because i32 has no lifetime. In your situation, you need to make life at the core of the function explicit:

 type TypeFn<'a> = fn(s: &'a str); 

Obviously, this also pops up to the structure:

 #[derive(Clone)] struct MyStruct<'a> { field: TypeFn<'a> } 

This prevents the following code:

 let my_var = MyStruct{field: my_fn}; let s = String::new(); (my_var.field)(&s); 

Actually the problem is that this is a mistake. As shown in @MattBrubeck answer Function pointers implement Copy . Thus, you can simply implement Clone manually using the Copy impl function pointer:

 impl Clone for MyStruct { fn clone(&self) -> Self { MyStruct { field: self.field, } } } 
+3
source

Function pointers with references in their types do not implement Clone due to issue # 24000 . This means that you cannot #[derive(Clone)] for types containing them; you must execute it manually.

But pointers to Copy functions, so you can impl Copy for your type, and then use it manually impl Clone :

 impl Copy for MyStruct {} impl Clone for MyStruct { fn clone(&self) -> Self { *self } } 

link to playpen .

+8
source

All Articles