Update reference_counting example to have a shared mutable value

This commit is contained in:
Timothy Warren 2019-02-05 10:44:22 -05:00
parent f9dcd6d48d
commit 9347fea052

View File

@ -1,19 +1,28 @@
#[derive(Debug)]
enum List { enum List {
Cons(i32, Rc<List>), Cons(Rc<RefCell<i32>>, Rc<List>),
Nil, Nil,
} }
use List::{Cons, Nil}; use List::{Cons, Nil};
use std::rc::Rc; use std::rc::Rc;
use std::cell::RefCell;
fn main() { fn main() {
let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); let value = Rc::new(RefCell::new(5));
println!("count after creating a = {}", Rc::strong_count(&a));
let _b = Cons(3, Rc::clone(&a)); let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil)));
println!("count after creating b = {}", Rc::strong_count(&a)); println!("a before = {:?}", a);
{
let _c = Cons(4, Rc::clone(&a)); let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a));
println!("count after creating c = {}", Rc::strong_count(&a)); println!("b before = {:?}", b);
}
println!("count after c goes out of scope = {}", Rc::strong_count(&a)); let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a));
println!("c before = {:?}", a);
*value.borrow_mut() += 10;
println!("a after = {:?}", a);
println!("b after = {:?}", b);
println!("c after = {:?}", c);
} }