Last active
March 8, 2020 12:48
-
-
Save ghosty141/cc60d8dc3a53e432d28810f5811e99d1 to your computer and use it in GitHub Desktop.
Using RefCell for multiple mutable references
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::cell::RefCell; | |
fn main() { | |
let a = A { | |
msg: String::from("Hi!"), | |
}; | |
let x = RefCell::new(a); | |
let b = B { b: &x }; | |
let c = C { c: &x }; | |
b.b.borrow_mut().say_hi(); | |
c.c.borrow_mut().msg = String::from("Bye!"); | |
b.b.borrow_mut().say_hi(); | |
} | |
pub struct A { | |
msg: String, | |
} | |
impl A { | |
pub fn say_hi(&mut self) { | |
println!("{}", self.msg); | |
} | |
} | |
struct B<'a> { | |
b: &'a RefCell<A>, | |
} | |
struct C<'a> { | |
c: &'a RefCell<A>, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment