1

I am passing a value out of block into a vec. The vec holds structs that owns an arr and a reference from that arr. Rusts borrow checker says that the reference does not live long enough. This is perplexing to me because the arr does live on outside the block because its memory is passed to the arr. I'm clearly not understanding something about rust lifetimes.

struct Holder1<'a> {
    owned_arr: Vec<i32>,
    hold: Holder2<'a>
}
struct Holder2<'a> {
    held: &'a i32
}

fn main() {
    let mut arr = vec![];
    {
        let nums = vec![1,2,3];
        let h = Holder1{
            owned_arr: nums,
            hold: Holder2 {
                held: &nums[0]
            }
        };
        arr.push(h);
    }
}
  • Please include the full error message in the question. – Ivan C Feb 07 '21 at 15:12
  • Welcome to Stack Overflow! Please search for existing questions before asking; the linked one is the most-frequently-linked to question in the [tag:rust] tag. This is a common frustration for people new to the language because Rust's focus on correct and unambiguous ownership isn't a feature of any other major language. The usual advice for a situation like yours is to store an index in `Holder2` and use it to index `owned_arr` instead of a reference. – trent Feb 07 '21 at 15:17

0 Answers0