I have a struct X
with 2 fields owned
and refed
, used to hold ownership and reference of numbers passed in by the insert
function.
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);
}
When I run this, I get the following error:
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
I'm surprised that the compiler thinks n
will no longer be available after the function ends, even though its ownership was already transferred and extended. So how do we get around this?