我的结构X
包含2个字段owned
和refed
,用于保存insert
函数传入的数字的所有权和引用。
fn main() {
struct X<'a> {
owned: Vec<i32>,
refed: Vec<&'a i32>
}
impl<'a> X<'a> {
fn insert(&mut self, n: i32) {
self.owned.push(n);
self.refed.push(&n);
}
}
let mut x = X { owned: vec![], refed: vec![] };
x.insert(1);
}
当我运行它时,我收到以下错误:
error: `n` does not live long enough
--> <anon>:10:30
|
10 | self.refed.push(&n);
| ^ does not live long enough
11 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the lifetime 'a as defined on unknown free region bounded by scope CodeExtent(36/CallSiteScope { fn_id: NodeId(24), body_id: NodeId(68) })...
error: aborting due to previous error
我很惊讶编译器认为n
在函数结束后将不再可用,即使其所有权已经转移和扩展。那么我们如何解决这个问题?