应为实现"FnMut"特性的闭包,但此闭包仅实现"FnOnce"

  • 本文关键字:quot 实现 闭包 FnOnce FnMut rust
  • 更新时间 :
  • 英文 :

fn main() {
let mut x = String::new();
let y = || {
let t = x;
};
let mut ww = Box::new(y);
ww();
}

我希望它能在没有任何错误的情况下运行,因为这个实现存在

impl<Args, F, A> FnOnce<Args> for Box<F, A> 

但我犯了一些奇怪的错误,我不明白为什么?

error[E0525]: expected a closure that implements the `FnMut` trait, but this closure only implements `FnOnce`
--> src/main.rs:22:13
|
22 |     let y = || {
|             ^^ this closure implements `FnOnce`, not `FnMut`
23 |         let t = x;
|                 - closure is `FnOnce` because it moves the variable `x` out of its environment
...
26 |     ww();
|     ---- the requirement to implement `FnMut` derives from here
error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce`
--> src/main.rs:22:13
|
22 |     let y = || {
|             ^^ this closure implements `FnOnce`, not `Fn`
23 |         let t = x;
|                 - closure is `FnOnce` because it moves the variable `x` out of its environment
...
26 |     ww();
|     ---- the requirement to implement `Fn` derives from here

[社区工作进行中]

一个解决方案是取消引用自己:

(*ww)();

现在编译器为什么这么做:

Box包含FnOnce,但默认情况下它似乎调用FnMut请参阅Boxed闭包调用如何像闭包调用一样工作?

当你这样做:

let mut ww = Box::new(y);
ww();

假设调用deref,并为box实现Deref,但通过borowing box返回&TFnOnce需要移动箱子。为什么要做这项工作?CCD_ 8和CCD_。这很奇怪。*可以称之为魔法特质吗?https://doc.rust-lang.org/std/ops/trait.CoerceUnsized.html?https://doc.rust-lang.org/std/ops/trait.DispatchFromDyn.html?

最新更新