使用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 这个操作的
一股坏代码的味道,坏在:你已经知道了 Rust 的借用规则,还要 对借用的东西 drop, 那么 Rust 借用还有什么用?