3

I have a vector of functiony enums. I want to clone this vector en masse. However, my Action enum can't derive Clone because Clone isn't implemented for a

fn(&mut Vec<i32>) 

It works if it's

fn(Vec<i32>) 

though. It doesn't seem to like fns that borrow their parameters. Why is this? Is there a way for me 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(); } 
1

1 Answer 1

3

The current implementation of Clone for fns isn't complete, so this isn't possible as-is, though it's intended to be fixed at some point.

In the meantime one thing you can do, albeit at the cost of an extra indirection, is to put it inside something like an Rc or Arc, since that is indeed Clone.

See this example which assumes you want thread-safety, hence the Arc, though a simple Rc may 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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.