【发布时间】:2018-05-25 18:54:04
【问题描述】:
我正在尝试创建一个特性,该特性应该对具有不同数量参数的函数/闭包进行抽象。像这样的:
trait MyTrait {}
impl MyTrait for Box<Fn() -> &'static str> {}
impl MyTrait for Box<Fn(u8) -> u8> {}
最初我打算这样使用它:
fn myf<F: MyTrait>(_fun: F) {}
fn main() {
myf(Box::new(|i: u8| i + 2))
}
但此代码失败并出现错误:
error[E0277]: the trait bound `std::boxed::Box<[closure@src/main.rs:11:18: 11:31]>: MyTrait` is not satisfied
当我像这样投射盒子时,一切都会正确编译:
myf(Box::new(|i: u8| i + 2) as Box<Fn(_) -> _>)
为什么 Rust 编译器不能在没有强制转换的情况下推断出这个特征?我的方法(使用演员表)是否正确,还是有更简单的方法?我更喜欢为我的项目启用trivial_casts 警告,这种语法会触发它。
【问题讨论】: