预期特征 core::ops::FnMut,找到类型参数 [英] expected trait core::ops::FnMut, found type parameter

查看:27
本文介绍了预期特征 core::ops::FnMut,找到类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么下面的代码不能编译.似乎 rust 只是没有扩展"类型参数,因为它看起来与我匹配.

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.

代码(防锈围栏:http://is.gd/gC82I4)

use std::sync::{Arc, Mutex};

struct Data{
    func: Option<Box<FnMut(String) + Send>>
}

fn newData<F>(func: Option<Box<F>>) -> Data
where F: FnMut(String) + Send{
    Data{
        func: func
    }
}

fn main(){
    let _ = newData(Some(Box::new(|msg|{})));
}

错误

<anon>:10:15: 10:19 error: mismatched types:
 expected `core::option::Option<Box<core::ops::FnMut(collections::string::String) + Send>>`,
    found `core::option::Option<Box<F>>`
(expected trait core::ops::FnMut,
    found type parameter) [E0308]
<anon>:10         func: func
                        ^~~~
error: aborting due to previous error
playpen: application terminated with error code 101

推荐答案

你需要通过拼写从 BoxBox 至少部分.

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

因为Box 隐含了Box,所以还需要加上绑定的F: 'static.

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

struct Data {
    func: Option<Box<FnMut(String) + Send>>
}

fn new_data<F>(func: Option<Box<F>>) -> Data where
    F: FnMut(String) + Send + 'static
{
    Data {
        func: func.map(|x| x as Box<_>)
    }
}

fn main() {
    let _ = new_data(Some(Box::new(|msg|{ })));
}

这里要注意的是,BoxBox 不是同一种类型,但前者会自动转换为后者在大多数情况下.在此处的 Option 中,我们只需要通过编写显式强制转换来帮助转换.

To note here is that Box<F> and Box<FnMut ...> 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.

这篇关于预期特征 core::ops::FnMut,找到类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆