Last active
August 29, 2015 14:23
-
-
Save lschmierer/c78226a53751756f75d1 to your computer and use it in GitHub Desktop.
Veiled RefCell in Rust
This file contains hidden or 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::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