I'm new to Rust. I'm learning Rust from "The Rust Programming Language" book on official rust-lang website. There is a code to find the first word from a string in the Slice Type section of "Understanding Ownership" chapter. The code is as below.
fn main() {
let mut greeting = String::from("Hello, Rust!");
let word = first_word(&greeting);
greeting.clear();
println!("{}", word);
}
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
I get the following compiler error.
error[E0502]: cannot borrow `greeting` as mutable because it is also borrowed as immutable
--> src/main.rs:5:5
|
3 | let word = first_word(&greeting);
| --------- immutable borrow occurs here
4 |
5 | greeting.clear();
| ^^^^^^^^^^^^^^^^ mutable borrow occurs here
6 | println!("{}", word);
| ---- immutable borrow later used here
The problem here is about the immutable borrow that the first_word
function has. What I don't understand is that, any function should drop all references it has when it goes out of scope. So why is the immutable borrow of greeting
still in the scope? It should have been dropped after the third line.
I guess I'm doing something wrong in the first_word
function and the immutable borrow is not dropped because of that. I don't really know what to do here.
I would appreciate if anyone can give an explanation on this. Thank you!
The problem here was that I misunderstood the concept of refrences a little bit. I assumed that the string slice returned by the first_word
function is a different object than the actual string so it would not be considered a reference to the actual string. But, because the slice type itself has a reference to the actual string object, the word
variable indirectly has a reference to the actual string. Because of that the string was still considered borrowed.
It was my misunderstanding in the concept. Sorry for the trouble.