How do I clone a closure, so that their types are the same?

后端 未结 4 1135
半阙折子戏
半阙折子戏 2020-12-07 03:51

I have a struct which looks something like this:

pub struct MyStruct
where
    F: Fn(usize) -> f64,
{
    field: usize,
    mapper: F,
    // fie         


        
4条回答
  •  时光取名叫无心
    2020-12-07 04:12

    You can't Clone closures. The only one in a position to implement Clone 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 a fn(usize) -> f64 instead, since they don't have a captured environment (any zero-sized closure can be rewritten as a function), and are Copy.

提交回复
热议问题