diff options
-rw-r--r-- | smart_pointer/src/main.rs | 28 |
1 files changed, 17 insertions, 11 deletions
diff --git a/smart_pointer/src/main.rs b/smart_pointer/src/main.rs index 6778671..a812ca0 100644 --- a/smart_pointer/src/main.rs +++ b/smart_pointer/src/main.rs @@ -1,7 +1,9 @@ // Recursive type using boxes use std::rc::Rc; +use std::cell::RefCell; +#[derive(Debug)] enum List { - Cons(i32, Rc<List>), + Cons(Rc<RefCell<i32>>, Rc<List>), Nil, } @@ -39,7 +41,10 @@ fn main() { println!("b = {}", b); use crate::List::{Cons, Nil}; - let list = Cons(1, Rc::new(Cons(2, Rc::new(Cons(3, Rc::new(Nil)))))); + let list = Cons(Rc::new(RefCell::new(1)), + Rc::new(Cons(Rc::new(RefCell::new(2)), + Rc::new(Cons(Rc::new(RefCell::new(3)), + Rc::new(Nil)))))); // Dereferencing let x = 5; @@ -81,13 +86,14 @@ fn main() { drop(c); println!("CustomSmartPointer dropped before the end of 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))); + let b = Cons(Rc::new(RefCell::new(3)), Rc::clone(&a)); + let c = Cons(Rc::new(RefCell::new(4)), Rc::clone(&a)); + + *value.borrow_mut() += 10; + + println!("a after = {:?}", a); + println!("b after = {:?}", b); + println!("c after = {:?}", c); } |