The clone is not implemented in a function ... sometimes

I have a vector of function enums. I want to clone this vector in bulk. However, my Action enum cannot receive Clone because Clone is not implemented for

fn(&mut Vec<i32>)

      

It works if it

fn(Vec<i32>)

      

though. It doesn't seem like fns borrowing their parameters. Why is this? Is there a way to do this?

#[derive(Clone)]
enum Action {
    Function (fn(&mut Vec<i32>))
}
fn pop(vec:&mut Vec<i32>) {
    let _ = vec.pop();
}
fn main() {
    let actions = vec![ Action::Function(pop), Action::Function(pop) ];
    let actions_copy = actions.to_vec();
}

      

+3


source to share


1 answer


The current implementation Clone

for fn

is incomplete , so it is not possible as-is, although it is intended to be committed at some point.

In the meantime, one thing you can do, albeit at the cost of additional indirection, is to put it in something like Rc

or Arc

, as it really is Clone

.

See this example, which assumes you need thread safety, hence Arc

, although a simple one Rc

might suffice in your case:



use std::sync::Arc;

#[derive(Clone)]
enum Action {
    Function (Arc<fn(&mut Vec<i32>)>)
}
fn pop(vec:&mut Vec<i32>) {
    let _ = vec.pop();
}
fn main() {
    let actions = vec![ Action::Function(Arc::new(pop)), Action::Function(Arc::new(pop)) ];
    let actions_copy = actions.to_vec();
}

      

playpen

+3


source







All Articles