Shared and Unique Borrows
Rust puts constraints on the ways you can borrow values:
- You can have one or more
&T
values at any given time, or - You can have exactly one
&mut T
value.
fn main() {
let mut a: i32 = 10;
let b: &i32 = &a;
{
let c: &mut i32 = &mut a;
*c = 20;
}
println!("a: {a}");
println!("b: {b}");
}
- The above code does not compile because
a
is borrowed as mutable (throughc
) and as immutable (throughb
) at the same time. - Move the
println!
statement forb
before the scope that introducesc
to make the code compile. - After that change, the compiler realizes that
b
is only ever used before the new mutable borrow ofa
throughc
. This is a feature of the borrow checker called “non-lexical lifetimes”.