From addc4ab037ed8d0635841e5ca9db3a1768c42a11 Mon Sep 17 00:00:00 2001 From: Jordan Gong Date: Mon, 21 Sep 2020 15:27:25 +0800 Subject: Mutate immutable data `RefCell` --- smart_pointer/src/main.rs | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) (limited to 'smart_pointer') 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), + Cons(Rc>, Rc), 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); } -- cgit v1.2.3