expected trait core::ops::FnMut, found type parameter

前端 未结 2 352
猫巷女王i
猫巷女王i 2020-12-21 04:42

I don\'t understand why the code below does not compile. It seems like rust is just not \'expanding\' the type parameter, since it looks like it matches to me.

Code

2条回答
  •  执笔经年
    2020-12-21 05:21

    You need to help rust by spelling out the cast from Box to Box at least partly.

    Because Box implies Box, you need to add the bound F: 'static too.

    struct Data {
        func: Option>
    }
    
    fn new_data(func: Option>) -> Data where
        F: FnMut(String) + Send + 'static
    {
        Data {
            func: func.map(|x| x as Box<_>)
        }
    }
    
    fn main() {
        let _ = new_data(Some(Box::new(|msg|{ })));
    }
    

    To note here is that Box and Box are not the same type, but the former will convert to the latter automatically in most cases. Inside the Option here we just needed to help the conversion by writing an explicit cast.

提交回复
热议问题