Last active
July 3, 2017 01:31
-
-
Save Sgeo/0612efbe561b4883e7c79607e52e0a02 to your computer and use it in GitHub Desktop.
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
use std::marker::PhantomData; | |
use std::cell::Cell; | |
struct Scope<'s> { | |
num: Cell<usize>, | |
phantom: PhantomData<Cell<&'s mut ()>>, | |
//ms: Vec<&'s mut i32>, <-- useful trick for understanding lifetimes | |
} | |
impl<'s> Scope<'s> { | |
fn take<'a: 's>(&self, m: &'a mut i32) -> &Cell<usize> { | |
//self.ms.push(m); <-- useful trick for understanding lifetimes | |
// ... | |
&self.num | |
} | |
} | |
fn scope<'s, R, F: FnOnce(&Scope<'s>) -> R>(f: F) -> R { | |
let r; | |
{ | |
let scope = Scope { | |
num: Cell::new(0), | |
phantom: PhantomData, | |
//ms: Vec::new(), <-- useful trick for understanding lifetimes | |
}; | |
r = f(&scope); | |
} | |
r | |
} | |
fn main() { | |
let mut a: i32 = 0; | |
let mut c: i32 = 0; | |
scope(|scope| { | |
let ca = scope.take(&mut a); | |
let cc = scope.take(&mut c); | |
let mut b: i32 = 0; | |
//scope.take(&mut b); | |
// ^^ uncomment for compilation failure | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment