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

时间:2019-04-30 14:18:29

标签: rust borrow

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

1 个答案:

答案 0 :(得分:3)

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

#models/resultvalue.rb

class Resultvalue < ApplicationRecord
    serialize :values, Array 
end

link to playground

但是在您的示例中,/// 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); } 首先出现,并且在评估第二个参数时,它已经被借用了。