Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rust borrowing rules - reference scope and non-lexical lifetimes
// Example of non-lexical lifetimes for references in Rust
//
// References go out of scope at their last use,
// not at the end of a block.
fn main() {
example1();
example2();
example3();
}
fn example1() {
let mut var = 1;
let r1 = &mut var;
*r1 += 1;
// First reference is now out of scope
// Can borrow again
let r2 = &mut var;
*r2 -= 1;
}
fn example2() {
let mut var = 1;
let r1 = &mut var;
*r1 += 1;
let r2 = &mut var;
*r2 -= 1;
// Compiler error - can not have multiple mutable references
// Using reference again keeps it it scope
// *r1 += 1;
}
fn example3() {
let mut var = 1;
let r1 = &mut var;
*r1 += 1;
let r2 = &mut var;
*r2 -= 1;
// Solution - define a new reference
// Allows both previous references to go out of scope
// Can use shadowing
let r1 = &mut var;
*r1 += 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.