0

I want to implement a tree whose node has parent field using Rust. From the official guide adding-a-reference-from-a-child-to-its-parent, they use the structure

struct Node {
    value: i32,
    parent: RefCell<Weak<Node>>,
    children: RefCell<Vec<Rc<Node>>>,
}

To use an instance of RefCell<Rc<T>> mutably, I can call .borrow_mut().

In the doc of std::cell, let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new())); is used to introduce mutability to Rc.

If I want a tree with parents which can be mutated, which one is recommended?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Evian
  • 1,035
  • 1
  • 9
  • 22
  • 1
    `RefCell` has more strict borrowing control: you can get only one mutable reference on data. `Rc`, allows having many mutable references at a time. So for your case `RefCell` is better. – Zefick Aug 14 '19 at 05:07
  • @Zefick What if T is a struct and I want to change some fields of T in RefCell>? Am I supposed to use RefCell>>? – Evian Aug 14 '19 at 05:23
  • Yes because in this case, you have two independently mutable entities - counted reference to T and T itself, Each of this needs its own `RefCell`. – Zefick Aug 14 '19 at 05:36

0 Answers0