Skip to content

Instantly share code, notes, and snippets.

@Sgeo
Last active July 3, 2017 01: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 Sgeo/0612efbe561b4883e7c79607e52e0a02 to your computer and use it in GitHub Desktop.
Save Sgeo/0612efbe561b4883e7c79607e52e0a02 to your computer and use it in GitHub Desktop.
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