Update reference_counting example to have a shared mutable value
This commit is contained in:
parent
f9dcd6d48d
commit
9347fea052
@ -1,19 +1,28 @@
|
||||
#[derive(Debug)]
|
||||
enum List {
|
||||
Cons(i32, Rc<List>),
|
||||
Cons(Rc<RefCell<i32>>, Rc<List>),
|
||||
Nil,
|
||||
}
|
||||
|
||||
use List::{Cons, Nil};
|
||||
use std::rc::Rc;
|
||||
use std::cell::RefCell;
|
||||
|
||||
fn main() {
|
||||
let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
|
||||
println!("count after creating a = {}", Rc::strong_count(&a));
|
||||
let _b = Cons(3, Rc::clone(&a));
|
||||
println!("count after creating b = {}", Rc::strong_count(&a));
|
||||
{
|
||||
let _c = Cons(4, Rc::clone(&a));
|
||||
println!("count after creating c = {}", Rc::strong_count(&a));
|
||||
}
|
||||
println!("count after c goes out of scope = {}", Rc::strong_count(&a));
|
||||
let value = Rc::new(RefCell::new(5));
|
||||
|
||||
let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil)));
|
||||
println!("a before = {:?}", a);
|
||||
|
||||
let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a));
|
||||
println!("b before = {:?}", b);
|
||||
|
||||
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);
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user