I have 2 example code.
1st Example Code
fn main() {
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = & s;
println!("{}", r2);
}
2nd Example Code
fn main() {
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = & s;
println!("{}", r1);
}
What I confuse is why 1stExampleCode
work fine, but 2ndExampleCode
create compile error as below
cannot borrow 's' as immutable because it is also borrowed as mutable
As I know, in both Example code I borrow r1
did a mutable borrow of s
while r2
did a immutable borrow of s
. So why 1stExampleCode
is not error since s
is borrowed as both mutable
and immutable
at the same time. Or because r1
is not used so it's not create any error.
The trick is that Rust refuses to have both borrows at once (because one is
mut
). However, in one case, Rust accepts the code because it can drop one of the borrows before the other one is given. That would be your first example. Indeed, ther1
variable is dropped (implicitly, by Rust) just beforer2
is assigned, which is possible because you never use it again (in fact, you never use it at all, but whatever).In the second case, however, Rust cannot do that, because between the creation and the usage of the first borrow, you create the second, that is, it's impossible to
drop
one when the other starts to be valid.