fn main() {
    let mut a = String::from("dd");
    let mut x = move || {
        a.push_str("string: &str");
    };
    x();
    x();
}

我在这里添加了move来捕获a,但是我仍然能够两次调用x闭包。 a是否仍在此处用作可变引用?为什么move不强制 move ?

最佳答案

变量a确实已移至闭包中:

fn main() {
    let mut a = String::from("dd");
    let mut x = move || {
        a.push_str("string: &str");
    };
    x();
    x();

    a.len();
}

error[E0382]: borrow of moved value: `a`
 --> src/main.rs:9:5
  |
2 |     let mut a = String::from("dd");
  |         ----- move occurs because `a` has type `std::string::String`, which does not implement the `Copy` trait
3 |     let mut x = move || {
  |                 ------- value moved into closure here
4 |         a.push_str("string: &str");
  |         - variable moved due to use in closure
...
9 |     a.len();
  |     ^ value borrowed here after move

目前尚不清楚为什么您认为闭包x在调用后会变得无效,但事实并非如此。应用于结构的内容相同:
struct ClosureLike {
    a: String,
}

impl ClosureLike {
    fn call(&mut self) {
        self.a.push_str("string: &str");
    }
}

fn main() {
    let a = String::from("dd");
    let mut x = ClosureLike { a };
    x.call();
    x.call();
}

关于rust - 即使将变量移入了闭包,为什么仍能两次调用它呢?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57470283/

10-12 06:54