Borrow checker behaves differently based on reference use

33 views Asked by At

The code below compiles only when line 11 is commented:

#[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]
}

The compiler says:

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. What happens to snapshot after content.clear() ? Is it dropped ?
  2. It seems to me that both immutable and mutable borrows are happening regardless of line 11. But, why is the compiler throwing an error only when it is not commented?
  3. Is this because of the rule any borrow must last for a scope no greater than that of the owner. If so, can you please elaborate more to clarify this?
0

There are 0 answers