我正在尝试实现一个查找函数,该函数将返回对 self
值中包含的值的可变引用。通常,由于返回的引用指向 lookup
函数 (self.verts
) 之外拥有的数据,借用检查器认为这没有问题。然而,就我而言,我会在返回引用并将其绑定(bind)到新的拥有名称之前过滤 self.verts 。当我尝试从本地拥有的数组返回值时,出现编译时错误:
error: `vs` does not live long enough
--> src/util/graph.rs:18:37
|
18 | if vs.len() > 0 { Some(&mut vs[0]) } else { None }
| ^^ does not live long enough
19 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the body at 16:75...
--> src/util/graph.rs:16:76
|
16 | pub fn lookup_id<'a>(&'a mut self, id: &str) -> Option<&'a mut Vertex> {
| ____________________________________________________________________________^ starting here...
17 | | let vs:Vec<&mut Vertex> = self.verts.iter_mut().filter(|x| x.id == id).collect();
18 | | if vs.len() > 0 { Some(&mut vs[0]) } else { None }
19 | | }
| |_____^ ...ending here
我知道我无法返回对本地拥有内容的引用,并且我怀疑这就是编译器解释我的代码的方式,但这不是我想要做的。想要做的是返回对 self.verts 向量中的值的引用,以便返回的引用具有相同的生命周期和正在执行查找的结构。这是我当前的尝试:
pub fn lookup_id<'a>(&'a mut self, id: &str) -> Option<&'a mut Vertex> {
let vs:Vec<&'a mut Vertex> = self.verts.iter_mut().filter(|x| x.id == id).collect();
if vs.len() > 0 { Some(&mut vs[0]) } else { None }
}
此代码无法编译,因为 vs 的生存时间不够长
。如何告诉编译器要返回 vs
中包含的引用而不是对 vs
的引用?
最佳答案
您正在返回&mut &mut Vertex
。
如果您要丢弃其余元素,则可以进行惰性计算:
self.verts.iter_mut().filter(|x| x.id == id).next()
关于rust - 返回对外部引用的过滤向量的引用时如何安抚借用检查器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42618450/