使用Refcell时,引用卡住了对Ref的手动释放怎么办
遇到了这样的问题(使用了comrak crate)
use ...
fn dialog<'a>(txt: &str, ext: &'a AstNode<'a>)-> Result<String>{...}
fn work(txt: &str){
let options = init();
let arena = Arena::new();
let root : &Node<'_, RefCell<Ast>>= parse_document(&arena, txt, &options);
for child in root.children(){
match ...{
NodeValue::Paragraph => {
let g_child :Ref<'_, Ast> = child.first_child().unwrap().data.borrow();
let value = &g_child.value
match value {
NodeValue::Text(txt) => {
mem::drop(g_child);
let html = dialog(&txt, child).unwrap();
println!("speech: {html}");
},
_ => ()
}
},
_ => ()
}
}
}
因为Refcell借用检查被放置到了运行时,而这里的dialog函数的第二个参数在函数体中也会对child.first_child().unwrap().data
进行borrow_mut()调用,这样会与work中的g_child有借用冲突(borrow和borrow_mut不能同时存在),那么我想手动drop掉g_child,但是match需要&g_child.value值来判断,但引用是无法drop的,那么g_child也无法drop,这样就被卡住了。
我想到了两种方案,一种是使用clone(),但性能有损;还就是用裸指针,但这就要unsafe了,但感觉小题大做。
大佬们有更好的解决方案吗
用clone吧,不过可能还有其他问题。
逻辑思路,限制了你对RUST的灵活应用。
怎么想到直接 mem::drop 这个操作的 :joy: 一股坏代码的味道,坏在:你已经知道了 Rust 的借用规则,还要 对借用的东西 drop, 那么 Rust 借用还有什么用?