I'm new to Rust and I'm reading the The Rust Programming Language online book. I'm now stuck on a problem about the Rust's borrow check, the code example is shown below:
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &b) in bytes.iter().enumerate() {
if b == b' ' {
return &s[..i];
}
}
&s[..]
}
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear();
println!("word = {}", word);
}
Rust compiler complains about the code with the following error message:
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--> src/main.rs:16:5
|
15 | let word = first_word(&s);
| -- immutable borrow occurs here
16 | s.clear();
| ^^^^^^^^^ mutable borrow occurs here
17 |
18 | println!("word = {}", word);
| ---- immutable borrow later used here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
error: Could not compile `demo`.
To learn more, run the command again with --verbose.
The online book explains that when executing s.clear()
, a new mutable reference to s
is created and conflicted with the existing immutable reference word
because word
is not out of its scope until the last println!
statement. It seems like that somehow, Rust's borrow checker figured out that word
, which is returned by the first_word
function, refers to s
. How does it achieve that?