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

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

    You can use trait objects to be able to implement Сlone for your struct:

    use std::rc::Rc;
    
    #[derive(Clone)]
    pub struct MyStructRef<'f>  {
        field: usize,
        mapper: &'f Fn(usize) -> f64,
    }
    
    
    #[derive(Clone)]
    pub struct MyStructRc  {
        field: usize,
        mapper: Rc f64>,
    }
    
    fn main() {
        //ref
        let closure = |x| x as f64;
        let f = MyStructRef { field: 34, mapper: &closure };
        let g = f.clone();
        println!("{}", (f.mapper)(3));
        println!("{}", (g.mapper)(3));
    
        //Rc
        let rcf = MyStructRc { field: 34, mapper: Rc::new(|x| x as f64 * 2.0) };
        let rcg = rcf.clone();
        println!("{}", (rcf.mapper)(3));
        println!("{}", (rcg.mapper)(3));    
    }
    

提交回复
热议问题