src/borrowing/borrowck.md
Rust's borrow checker puts constraints on the ways you can borrow values. We've already seen that a reference cannot outlive the value it borrows:
<!-- mdbook-xgettext: skip --># // Copyright 2023 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
fn main() {
let x_ref = {
let x = 10;
&x
};
dbg!(x_ref);
}
There's also a second main rule that the borrow checker enforces: The aliasing rule. For a given value, at any time:
# // Copyright 2023 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
fn main() {
let mut a = 10;
let b = &a;
{
let c = &mut a;
*c = 20;
}
dbg!(a);
dbg!(b);
}
a is borrowed as mutable (through
c) and as immutable (through b) at the same time.
*c = 20 and show that the compiler error still occurs even
if we never use c.c isn't necessary to trigger a borrow
conflict. Replace c with a direct mutation of a and demonstrate that
this produces a similar error. This is because direct mutation of a value
effectively creates a temporary mutable reference.dbg! statement for b before the scope that introduces c to make
the code compile.
b is only ever used before
the new mutable borrow of a through c. This is a feature of the borrow
checker called "non-lexical lifetimes".