借用检查器的行为因参考用途而异

问题描述

以下代码仅在注释第 11 行时编译:

#[allow(warnings)]
fn main() {
    let mut content = String::from("Hello World!");

    let snapshot = get_slice(&content); // immutable borrow
    println!("content is : {}",&content);

    content.clear(); // mutable borrow fn clear(&mut self)

    println!("snapshot is : {}",snapshot); // should be commented for this to compile
}

fn get_slice(part: &str) -> &str {
    &part[0..5]
}

编译器说:

error[E0502]: cannot borrow `content` as mutable because it is also borrowed as immutable
  --> src/main.rs:8:5
   |
5  |     let snapshot = get_slice(&content); // immutable borrow
   |                              -------- immutable borrow occurs here
...
8  |     content.clear(); // mutable borrow fn clear(&mut self)
   |     ^^^^^^^^^^^^^^^ mutable borrow occurs here
9  | 
10 |     println!("snapshot is : {}",snapshot); // should be commented for this to compile
   |                                  -------- immutable borrow later used here
  1. snapshot 之后 content.clear() 会发生什么?掉线了吗?
  2. 在我看来,无论第 11 行如何,不可变借用和可变借用都会发生。但是,为什么编译器仅在没有注释时才抛出错误
  3. 这是因为规则 any borrow must last for a scope no greater than that of the owner。如果是这样,您能否详细说明一下以澄清这一点?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)