Hi,
I am writing a mutable tree and a depth first search function to mutate nodes. I wrote the following:
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Default)]
pub struct MutableTreeNode {
key: String,
children: Vec<Rc<RefCell<MutableTreeNode>>>
}
impl MutableTreeNode {
pub fn new() -> MutableTreeNode {
::std::default::Default::default()
}
}
fn dfs(root: MutableTreeNode, cb: &Fn(Rc<RefCell<MutableTreeNode>>)) {
let mut stack = Vec::<Rc<RefCell<MutableTreeNode>>>::new();
// ignore root during this DFS; use children
let root_children = root.children;
for child in root_children {
stack.push(child);
}
while !stack.is_empty() {
let node = stack.pop().unwrap();
cb(node);
let node_mut = node.borrow_mut();
let node_children = &node_mut.children;
for child in node_children {
stack.push(child);
}
}
}
I am getting the error for stack.push(child)
:
= note: expected type `std::rc::Rc<std::cell::RefCell<MutableTreeNode>>`
found type `&std::rc::Rc<std::cell::RefCell<MutableTreeNode>>`
My question is whether the type Vec<Rc<RefCell<MutableTreeNode>>>
for children will allow for mutability during DFS and, if so, how I can address the error.
I am new to Rust. Thanks!