Skip to content

Instantly share code, notes, and snippets.

@lschmierer
Last active August 29, 2015 14:23
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 lschmierer/c78226a53751756f75d1 to your computer and use it in GitHub Desktop.
Save lschmierer/c78226a53751756f75d1 to your computer and use it in GitHub Desktop.
Veiled RefCell in Rust
use std::rc::Rc;
use std::cell::RefCell;
struct Wrapper {
data_cell: RefCell<Data>,
}
struct Data {
num: u8,
}
impl Wrapper {
fn new() -> Rc<Wrapper> {
Rc::new(Wrapper {
data_cell: RefCell::new(Data { num: 0 }),
})
}
fn inc(&self) {
self.data_cell.borrow_mut().num += 1;
}
fn print(&self) {
println!("{}", self.data_cell.borrow().num)
}
}
fn main() {
let test = Wrapper::new();
test.print();
test.inc();
test.print();
let closure = || test.inc();
test.inc();
test.print();
closure();
test.print();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment