I'm learning Rust and the below code comes from the online book The Rust Programming Language link:
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear(); // error!
println!("the first word is: {}", word);
}
The compiler says below:
| let word = first_word(&s);
| -- immutable borrow occurs here
So I think "immutable borrow occurs here" is talking about &s
instead of "let word".
But if I change
let word = first_word(&s);
to
first_word(&s);
The compiler error disappears.
So it makes me feel that "immutable borrow occurs here" is talking about "let word" instead of &s
.
And if first_word
's return value depends only on another string (which means first_word
doesn't depends on the &s
at all) as below:
fn first_word(s: &String) -> &str {
println!("the input for first word is: {}", s);
let s1 = "hi rust";
let bytes = s1.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s1[0..i];
}
}
&s1[..]
}
The compiler still says below:
| let word = first_word(&s);
| -- immutable borrow occurs here
I am very confused about what the compiler does actually for generating "immutable borrow occurs here".