Hi, i did study snake game with std::collections::LinkedList but i dont understand the next code:
#[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(6)), Rc::clone(&a));
let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a));
*value.borrow_mut() += 10;
println!("a after = {:?}", a);
println!("b after = {:?}", b);
println!("c after = {:?}", c);
}
how does it work in memory ? interest ?
What is the difference between RefCell and Cell ?
An Rc heap allocates its contents. As for Cell and RefCell, they both have the purpose of modifying a value through a shared reference, but they differ in how they achieve this. The fundamental issue is that to gain a mutable reference to something, you must have exclusive access to it, so you can't just unconditionally create a mutable reference into a cell.
Cell achieves it by disallowing references to its contents, and requires all access to go through set, get and similar.
RefCell achieves it by counting how many references there are to the contents, and panicking if the rules are violated.