I'm not very skilled with rust RefCell
and i want to know how to solve the following error.
I would be very grateful if someone could answer my question.
use std::rc::Rc;
use std::cell::RefCell;
enum Node {
Branch { name: String },
Leaf { name: String },
}
fn test_match(node: &Rc<RefCell<Node>>) {
let borror_mut_node = RefCell::borrow_mut(node);
match borror_mut_node {
Node::Branch { name } => name.push_str("b"),
Node::Leaf { name } => name.push_str("l"),
}
}
fn main() {
let node = Node::Branch { name: "test-" };
let node = Rc::new(RefCell::new(node));
test_match(&node);
}
You will need to declare borror_mut_node
mutable, match on*borror_mut_node
and then take mutable reference to the inner field.
fn test_match(node: &Rc<RefCell<Node>>) {
let mut borror_mut_node = RefCell::borrow_mut(node);
match *borror_mut_node {
Node::Branch { ref mut name } => name.push_str("b"),
Node::Leaf { ref mut name } => name.push_str("l"),
}
}
You can simplify it further by removing borror_mut_node
. You don't need it.
fn test_match(node: &Rc<RefCell<Node>>) {
//let borror_mut_node = RefCell::borrow_mut(node);
match *node.borrow_mut() {
Node::Branch { ref mut name } => name.push_str("b"),
Node::Leaf { ref mut name } => name.push_str("l"),
}
}
Another way is by matching on the mutable reborrow.
fn test_match(node: &Rc<RefCell<Node>>) {
//let borror_mut_node = RefCell::borrow_mut(node);
match &mut *node.borrow_mut() {
Node::Branch { name } => name.push_str("b"),
Node::Leaf { name } => name.push_str("l"),
}
}