为什么调用装箱闭包和调用闭包一样有效?是因为Deref实现了Box吗?它适用于所有智能指针吗?当我尝试一些例子来更好地理解它时,我得到了以下错误。
fn main() {
let mut x = String::new();
let y = || {
let t = &mut x;
};
let mut ww = Box::new(y);
(&mut ww)();
}
这会引发错误
error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnMut`
--> src/main.rs:22:13
|
22 | let y = || {
| ^^ this closure implements `FnMut`, not `Fn`
23 | let t = &mut x;
| - closure is `FnMut` because it mutates the variable `x` here
...
26 | (&mut ww)();
| ----------- the requirement to implement `Fn` derives from here
任何关于盒装封口如何工作的文档都会很有帮助。
Box实现了自Rust 1.35以来的所有FnX特性(这里有更多信息,来源(,因此它应该是可调用的。
在这种特殊情况下,编译器似乎不够聪明,无法将类型&mut Box<Closure>
取消引用并强制转换为预期的Box<impl FnMut() -> ()>
以直接执行调用。
这是可行的:
(ww as Box::<dyn FnMut() -> ()>)();
这也起作用:
ww.as_mut()()