Skip to content

Instantly share code, notes, and snippets.

@KevinWMatthews
Created June 28, 2019 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KevinWMatthews/bfd75c91adc6f23e8869992bd7c749c3 to your computer and use it in GitHub Desktop.
Save KevinWMatthews/bfd75c91adc6f23e8869992bd7c749c3 to your computer and use it in GitHub Desktop.
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