book
book copied to clipboard
ch15-05: simplify the code of mutable cons list
- [x] I have checked the latest
main
branch to see if this has already been fixed - [x] I have searched existing issues and pull requests for duplicates
URL to the section(s) of the book with this problem: https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#having-multiple-owners-of-mutable-data-by-combining-rct-and-refcellt
Description of the problem: In Listing 15-24, the List
is defined as below:
enum List {
Cons(Rc<RefCell<i32>>, Rc<List>),
Nil,
}
This might confuse the readers that to implement a mutable list, we always need to wrap a RefCell
with a Rc
. However, this is not true. As we are emphesizing the interior mutability gained by RefCell
, we can simplify above definition into:
enum List {
Cons(RefCell<i32>, Rc<List>),
Nil,
}
Together, with update to the following code as below:
fn main() {
let a = Rc::new(Cons(RefCell::new(1), Rc::new(Nil)));
let b = Cons(RefCell::new(2), Rc::clone(&a));
let c = Cons(RefCell::new(3), Rc::clone(&a));
if let Cons(v, _) = &*a {
*(v.borrow_mut()) = 2;
}
println!("{:?}", a);
println!("{:?}", b);
println!("{:?}", c);
}
This aligns better with the code in Listing 15-18.