首页 > 解决方案 > 为什么循环内的一些 while-let 分配无法编译,“不能一次多次借用可变”?

问题描述

struct Foo(Option<Box<Foo>>);

fn func(mut foo: Foo) {
    let mut bar = &mut foo;
    loop {
        // while let Some(next) = bar.0.as_mut() {  // version-1
        // while let Some(next) = &mut bar.0 {  // version-2
        while let Some(ref mut next) = bar.0 {  // version-3
            bar = next.as_mut();
        }
    }
}

锈游乐场

上面的代码中,只有version-3可以编译成功。我想知道这三个版本之间的区别以及为什么只有版本 3 是有效的。

请注意,在版本 3 中,bar.0似乎没有移动到左侧模式。一个简单的试验:

let mut a = Foo(Some(Box::new(Foo(None))));
if let Some(ref mut _b) = a.0 {
    // Foo does not implement the `Copy` trait
    println!("Go into if-let");
}
let b = a;  // Moving occurs here, so `a.0` is not moved

版本 1 的错误消息:

error[E0499]: cannot borrow `bar.0` as mutable more than once at a time
 --> src/lib.rs:6:32
  |
6 |         while let Some(next) = bar.0.as_mut() {  // version-1
  |                                ^^^^^ mutable borrow starts here in previous iteration of loop

版本 2 的错误消息:

error[E0499]: cannot borrow `bar.0` as mutable more than once at a time
 --> src/lib.rs:7:32
  |
7 |         while let Some(next) = &mut bar.0 {  // version-2
  |                                ^^^^^^^^^^ mutable borrow starts here in previous iteration of loop

标签: rust

解决方案


推荐阅读