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

后端 未结 4 1139
半阙折子戏
半阙折子戏 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:10

    As of Rust 1.26.0, closures implement both Copy and Clone if all of the captured variables do:

    #[derive(Clone)]
    pub struct MyStruct
    where
        F: Fn(usize) -> f64,
    {
        field: usize,
        mapper: F,
    }
    
    fn main() {
        let f = MyStruct {
            field: 34,
            mapper: |x| x as f64,
        };
        let g = f.clone();
        println!("{}", (g.mapper)(3));
    }
    

提交回复
热议问题