Confuse about borrowing in Rust

707 views Asked by At

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.

2

There are 2 answers

0
jthulhu On

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, the r1 variable is dropped (implicitly, by Rust) just before r2 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.

0
Nathan Ramli On

In the first example, the compiler is smart enough to know that the r1 is not used anymore after it's initialized because it's never called anymore. It also means the borrowed s is released after the initialized line of r1 and can be borrowed by others. So r2 can borrow it.

In the second example, r1 is borrowing s value with mutable reference. A mutable reference can only be borrowed by one variable. But r2 borrowing s variable while r1 still uses it in the println! line.

For more information, you can read this https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html