Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Why can borrow_mut() be called on a Rc that contains a RefCell?
Hello,
The related questions I read do not answer this question.
I am reading the Rust book RefCell<T> and the Interior Mutability Pattern - The Rust Programming Language
and have a question on this code snippet:
#[derive(Debug)]
enum List {
Cons(Rc<RefCell<i32>>, Rc<List>),
Nil,
}
use crate::List::{Cons, Nil};
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
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:?}");
}
To my understanding both Rc
and RefCell
are structs that among other things contain an element of generic type T
. value
is a Rc
that contains a RefCell<i32>
and borrow_mut
is a method on a RefCell
. So why is this method implemented for a Rc
? I just checked this in the documentation. Is it because they want to make possible the use of boxing a RefCell
inside it?
4 posts - 2 participants
🏷️ rust_feed