0

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);
}

fiddle

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?

Fabricator
  • 12,722
  • 2
  • 27
  • 40
  • In addition to the linked duplicate, the compiler is specifically complaining because you are trying to take a reference to the stack-allocated `i32` that was passed as an argument. You are **not** taking a reference to the `i32` that was stored in the vector. `i32` is a [`Copy`](https://doc.rust-lang.org/std/marker/trait.Copy.html) type. The linked duplicate is the answer you would run into next, once you took the reference to yourself ^_^. – Shepmaster Dec 21 '16 at 04:12
  • @Shepmaster, got it. Thanks for taking your time to explain this. – Fabricator Dec 21 '16 at 18:59

0 Answers0