当没有发生借用重叠时,为什么会出现借用错误?

问题描述 投票:4回答:1

以下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发生可变借用之前结束不可变借用。

rust borrow
1个回答
3
投票

论证的顺序很重要。例如,这有效:

/// 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);
}

(Qazxswpoi)

但在你的例子中,link to playground首先出现,在评估第二个参数时,它已经被借用了。

© www.soinside.com 2019 - 2024. All rights reserved.