Ichi
Ichi

Reputation: 369

Rust - why it does not give me an error when borrowed &mut twice

I am checking out this rust doc https://doc.rust-lang.org/1.30.0/book/2018-edition/ch04-02-references-and-borrowing.html

I will not see any error when I borrowed &mut twice (see the code below), can anyone tell me why?

let mut s = String::from("hello");

let r1 = &mut s;
let r2 = &mut s;

Upvotes: 1

Views: 147

Answers (1)

apetranzilla
apetranzilla

Reputation: 5949

This is due to non-lexical lifetimes. The compiler recognizes that, since the first reference is never used after the second is created (or at all, in your example), it can simply be dropped, allowing the second reference to be created.

If we attempt to extend the lifetime of the first reference with the below example, we'll get an error about having multiple mutable references, as expected:

let mut s = String::from("hello");

let r1 = &mut s;
let r2 = &mut s; // error[E0499]: cannot borrow `s` as mutable more than once at a time

drop(r1);

Upvotes: 3

Related Questions