I'm trying to understand how borrowing works in rust. So after read some topics of the rust book. I got stuck, trying to understand why this code doesn't compile.
Codefn main() {
let mut a = String::from("yes");
let b = function(&a);
a.clear();
println!("Hello {}", b);
}
fn function(a :&String) -> &str{
if a == "yes" {
"OK"
}
else{
"NO"
}
}
The compiler gives this error:
Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `a` as mutable because it is also borrowed as immutable
--> src/main.rs:4:5
|
3 | let b = function(&a);
| -- immutable borrow occurs here
4 | a.clear();
| ^^^^^^^^^ mutable borrow occurs here
5 | println!("Hello {}", b);
| - 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 `playground`.
To learn more, run the command again with --verbose.
But I don't understand why the scope of &a doesn't ends with the function scope.