Skip to content

Instantly share code, notes, and snippets.

@ghosty141
Last active March 8, 2020 12:48
Show Gist options
  • Save ghosty141/cc60d8dc3a53e432d28810f5811e99d1 to your computer and use it in GitHub Desktop.
Save ghosty141/cc60d8dc3a53e432d28810f5811e99d1 to your computer and use it in GitHub Desktop.
Using RefCell for multiple mutable references
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