以下代码由于借用错误而失败:
错误信息如下:
为什么这里会出现借用错误?
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
发生之前结束不可变借用。