如何匹配RefMut<Enum>?Rust RefCell使用问题求助
修复Rust RefCell使用中的错误
问题分析
- 拼写错误:
borror_mut应为borrow_mut - 类型不匹配:
"test-"是&str类型,但Node的name字段定义为String,需要做类型转换 - 匹配模式错误:
RefCell::borrow_mut返回RefMut<Node>智能指针,直接匹配会触发移动语义,需通过可变引用模式获取内部数据
修复后的代码
use std::rc::Rc; use std::cell::RefCell; enum Node { Branch { name: String }, Leaf { name: String }, } fn test_match(node: &Rc<RefCell<Node>>) { // 修正拼写,通过Rc直接调用borrow_mut获取可变引用 let mut node_ref = node.borrow_mut(); // 解引用智能指针,用&mut模式获取内部Node的可变引用 match &mut *node_ref { Node::Branch { name } => name.push_str("b"), Node::Leaf { name } => name.push_str("l"), } } fn main() { // 将字符串字面量转为String类型 let node = Node::Branch { name: "test-".to_string() }; let node = Rc::new(RefCell::new(node)); test_match(&node); }
关键说明
RefCell::borrow_mut返回的RefMut<T>是智能指针,必须通过解引用(*)+&mut的方式,才能获取内部数据的可变引用,进而修改name字段- 字符串字面量转
String可使用.to_string()或String::from()两种方式 node.borrow_mut()是更符合Rust习惯的调用方式,等价于RefCell::borrow_mut(node)
内容的提问来源于stack exchange,提问作者lost.sof
相关产品推荐
相关产品推荐

