diff options
author | Jordan Gong <jordan.gong@protonmail.com> | 2020-09-21 15:27:25 +0800 |
---|---|---|
committer | Jordan Gong <jordan.gong@protonmail.com> | 2020-09-21 15:27:25 +0800 |
commit | addc4ab037ed8d0635841e5ca9db3a1768c42a11 (patch) | |
tree | ebce411781a6eb109c76ebf84bc7687909e5acf8 /smart_pointer/src | |
parent | 5858e3d5c7033f09b7fb2c006a2e227d0cff3d89 (diff) |
Mutate immutable data `RefCell`
Diffstat (limited to 'smart_pointer/src')
-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); } |