【发布时间】:2020-12-29 02:52:39
【问题描述】:
我不明白我收到的以下代码的错误消息。
use std::collections::HashMap;
use std::rc::Weak;
struct ThingPool {
thing_map: HashMap<String, Thing>,
}
impl ThingPool {
pub fn get(&self, key: &str) -> Option<&Thing> {
self.thing_map.get(key)
}
}
struct Thing {
pool: Weak<RefCell<ThingPool>>,
key: String,
parent_key: String,
}
impl Thing {
pub fn parent(&self) -> Option<&Thing> {
let pool = &*self
.pool
.upgrade()
.expect("FATAL: ThingPool no longer exists")
.borrow();
pool.get(&self.parent_key)
}
}
fn main() {
// ...
}
我有一个事物的递归数据结构,我正在尝试编写一个方法来根据其键在 ThingPool 中查找特定事物的父级。我收到的错误消息是:
--> src/main.rs:30:9
|
24 | let pool = &*self
| ______________________-
25 | | .pool
26 | | .upgrade()
27 | | .expect("FATAL: ThingPool no longer exists")
28 | | .borrow();
| |_____________________- temporary value created here
29 |
30 | pool.get(&self.parent_key)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
我知道我不能返回对本地值的引用,但我不明白在这种情况下本地值是什么。什么是“当前函数拥有的数据”?我返回的值是 ThingPool 中 HashMap 的值。我没有复制pool,因此 HashMap 以及该值不应该是函数的本地值。我错过了什么?
【问题讨论】:
标签: rust