Skip to content

Instantly share code, notes, and snippets.

@ewust
Created July 9, 2016 17:33
Show Gist options
  • Save ewust/23260cf8bb2a1d0620de83af5d857c19 to your computer and use it in GitHub Desktop.
Save ewust/23260cf8bb2a1d0620de83af5d857c19 to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug)]
struct Bar {
x: u32,
}
struct Foo {
view_a: HashMap<u32, Rc<RefCell<Bar>>>,
view_b: HashMap<u32, Rc<RefCell<Bar>>>,
}
fn init_hash(foo: &mut Foo) {
let bar = Bar { x: 16 };
let ref_bar = RefCell::new(bar);
let rc_bar = Rc::new(ref_bar);
foo.view_a.insert(8, rc_bar.clone());
foo.view_b.insert(16, rc_bar.clone());
}
fn main() {
let mut foo = Foo {
view_a: HashMap::new(),
view_b: HashMap::new(),
};
init_hash(&mut foo);
{
if let Entry::Occupied(mut res) = foo.view_a.entry(8) {
let mut a: Rc<RefCell<Bar>> = *res.get_mut();
println!("View A: {:?}", a);
let b = a.get_mut();
//let b = (*a).try_unwrap();
println!("View A.get_mut(): {:?}", b);
//b.x = 12;
}
if let Entry::Occupied(mut res) = foo.view_b.entry(16) {
let a = res.get_mut();
println!("View B: {:?}", a);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment