error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--> src/main.rs:7:5
|
5 | let word = first_word(&s);
| - immutable borrow occurs here
6 |
7 | s.clear(); // Error!
| ^ mutable borrow occurs here
8 | }
| - immutable borrow ends here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
error: Could not compile `playground`.
To learn more, run the command again with --verbose.
My best guess is that the compiler determines word can be dropped before calling s.clear() since it is not used after s.clear(). Meaning it makes the code look like this:
#![allow(unused_variables)]
fn main() {
let mut s = String::from("hello world");
{
let word = first_word(&s);
// Word will be dropped here.
}
s.clear(); // Error!
}
I am not entirely sure this is the right reasoning though.