Created
December 28, 2020 21:41
-
-
Save boki1/0fe7a2dd25584124f32217e5cfe27a52 to your computer and use it in GitHub Desktop.
Interior Mutability Design Pattern - 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; | |
trait Component { | |
fn attach_to(&mut self, container: Rc<RefCell<Outer>>); | |
} | |
#[derive(Debug)] | |
struct Inner { | |
cont: Option<Rc<RefCell<Outer>>>, | |
ok: Option<String>, | |
} | |
impl Component for Inner { | |
fn attach_to(&mut self, container: Rc<RefCell<Outer>>) | |
{ | |
self.cont = Some(container); | |
self.ok = Some("ATTACHED".to_string()); | |
} | |
} | |
#[derive(Debug)] | |
struct Outer { | |
thing: Inner | |
} | |
impl Outer { | |
fn new() -> Rc<RefCell<Self>> { | |
let initial_value = Outer { thing: Inner { cont: None, ok: None }}; | |
let container = Rc::new(RefCell::new(initial_value)); | |
let thing = &mut container.borrow_mut().thing; | |
thing.attach_to(container.clone()); | |
container.clone() | |
} | |
} | |
fn main() { | |
let wrapper = Outer::new(); | |
let outer = &mut wrapper.borrow_mut(); | |
println!("{:?}", outer.thing.ok); | |
println!("{:?}", wrapper.as_ptr() == outer.thing.cont.as_ref().unwrap().as_ptr()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment