以下 code 因借用错误而失败:

extern crate chrono; // 0.4.6

fn main() {
    let mut now = chrono::Local::today();
    now = std::mem::replace(&mut now, now.succ());
}

错误是:

error[E0502]: cannot borrow `now` as immutable because it is also borrowed as mutable
 --> src/lib.rs:5:39
  |
5 |     now = std::mem::replace(&mut now, now.succ());
  |           ----------------- --------  ^^^ immutable borrow occurs here
  |           |                 |
  |           |                 mutable borrow occurs here
  |           mutable borrow later used by call

为什么这里会出现借用错误? now.succ() 返回一个新对象,看起来 succ() 调用应该返回新对象,在 replace 发生可变借用之前结束不可变借用。

最佳答案

参数的顺序很重要。例如这有效:

/// Same as `std::mem::replace`, but with the reversed parameter order.
pub fn replace<T>(src: T, dest: &mut T) -> T {
    std::mem::replace(dest, src)
}

fn main() {
    let mut now = chrono::Local::today();
    now = replace(now.succ(), &mut now);
}

( link to playground )

但是在您的示例中, &mut now 首先出现,并且在评估第二个参数时,它已经被借用了。

关于rust - 当没有发生借用重叠时,为什么会出现借用错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55922926/

10-11 18:34