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
- What happens to
snapshot
aftercontent.clear()
? Is it dropped ? - 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?
- 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?