[英]Obtain a reference from a RefCell<Option<Rc<T>>> in Rust
[英]'cannot return reference to temporary value' using Option<Rc<RefCell<T>>>
所以我有一些这样的代码:
use std::borrow::Borrow;
use std::cell::RefCell;
use std::collections::HashMap;
use std::ops::Index;
use std::rc::Rc;
struct Data {
// ...
}
struct TableTreeNode {
father: Option<Rc<RefCell<TableTreeNode>>>,
table: HashMap<String, Data>,
}
impl Index<&str> for TableTreeNode {
type Output = Data;
fn index(&self, index: &str) -> &Self::Output {
if self.table.contains_key(index) {
self.table.index(index)
} else {
//recursively goes up
let father: &RefCell<TableTreeNode> = self.father.as_ref().expect("not found");
father.borrow().index(index)
}
}
}
编译失败:
error[E0515]: cannot return reference to temporary value
--> xxx.rs:25:13
|
25 | father.borrow().index(index)
| ---------------^^^^^^^^^^^^^
| |
| returns a reference to data owned by the current function
| temporary value created here
我不知道如何解决这个问题。 从RefCell
借来的东西怎么会是一个临时变量? 如果我做错了,实现这些的正确方法是什么?
因为RefCell::borrow()
返回一个Ref
保护。 这个守卫实现Deref
,当它被丢弃时,它将RefCell
标记为不再被借用。
通常,如果您使用RefCell
,则无法跨越 API 边界隐藏它。 您必须返回Ref<Something>
或RefMut<Something>
而不是 os &[mut] Something
。 而且因为Index
的签名是恒定的并且期望引用,这意味着您无法实现Index
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.