Created
June 28, 2019 16:31
-
-
Save KevinWMatthews/bfd75c91adc6f23e8869992bd7c749c3 to your computer and use it in GitHub Desktop.
Rust borrowing rules - reference scope and non-lexical lifetimes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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