I have a struct which looks something like this:
pub struct MyStruct<F>
where
F: Fn(usize) -> f64,
{
field: usize,
mapper: F,
// fields omitted
}
How do I implement Clone
for this struct?
One way I found to copy the function body is:
let mapper = |x| (mystruct.mapper)(x);
But this results in mapper
having a different type than that of mystruct.mapper
.
As of Rust 1.26.0, closures implement both
Copy
andClone
if all of the captured variables do:You can use trait objects to be able to implement
Сlone
for your struct:You can use
Rc
(orArc
!) to get multiple handles of the same unclonable value. Works well withFn
(callable through shared references) closures.Remember that
#[derive(Clone)]
is a very useful recipe for Clone, but its recipe doesn't always do the right thing for the situation; this is one such case.You can't
Clone
closures. The only one in a position to implementClone
for a closure is the compiler... and it doesn't. So, you're kinda stuck.There is one way around this, though: if you have a closure with no captured variables, you can force a copy via
unsafe
code. That said, a simpler approach at that point is to accept afn(usize) -> f64
instead, since they don't have a captured environment (any zero-sized closure can be rewritten as a function), and areCopy
.