我有这个结构:
pub struct ImmEval<Out> {
closure: Rc<dyn Fn(&Self) -> Out>
}
impl<Out> From<Rc<dyn Fn(&Self) -> Out>> for ImmEval<Out> {
/// Constructs the evaluator from the specified closure.
fn from(cl: Rc<dyn Fn(&Self) -> Out>) -> Self {
ImmEval {closure: cl}
}
}
impl<Out> Evaluator for ImmEval<Out> {
type Output = Out;
/// Evaluates and returns the result.
fn eval(&self) -> Self::Output {
(*self.closure)(self)
}
}
在这样的测试中使用:
let counter = Cell::new(0);
{
let eval = ImmEval::<i32>::from(Rc::from(|_: &ImmEval<i32>| {
counter.set(counter.get() + 1);
counter.get()
}));
eval.eval();
eval.eval();
}
assert_eq!(counter.get(), 2);
结构本身会编译,但测试不会编译。相反,它失败并显示以下
rustc
消息:error[E0277]: the trait bound `ImmEval<i32>: std::convert::From<std::rc::Rc<[closure@src\tests.rs:8:51: 11:10 counter:_]>>` is not satisfied
--> src\tests.rs:8:41
|
8 | let eval = ImmEval::<i32>::from(Rc::from(|_: &ImmEval<i32>| {
| _________________________________________^
9 | | counter.set(counter.get() + 1);
10 | | counter.get()
11 | | }));
| |__________^ the trait `std::convert::From<std::rc::Rc<[closure@src\tests.rs:8:51: 11:10 counter:_]>>` is not implemented for `ImmEval<i32>`
|
= help: the following implementations were found:
<ImmEval<Out> as std::convert::From<std::rc::Rc<(dyn for<'r> std::ops::Fn(&'r ImmEval<Out>) -> Out + 'static)>>>
= note: required by `std::convert::From::from`
当然,这意味着我的封包不是有效的
Fn(&ImmEval<i32>) -> i32
,但是为什么呢?Here's the playground example。
最佳答案
在这种情况下无法进行类型推断。如果您编写所需的类型,则可以使用:
let f: Rc<dyn Fn(&ImmEval<i32>) -> i32> = Rc::new(|_: &ImmEval<i32>| {
counter.set(counter.get() + 1);
counter.get()
});
let eval = ImmEval::<i32>::from(f);
但这不能解决您的其他终生问题。
关于generics - 为什么不能在Rc <dyn Fn()>内使用此闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60207399/