Reference to struct wrapped in Option<>

I would like to have a 'load on demand' Vec and make a function that returns a reference to MyStruct if already loaded.

pub data: Vec<Option<MyStruct>> 
fn get_element(index: usize) -> &MyStruct
{
    // if self.data[index] != None
    // return ??
}

Hint: Start by doing a pattern match on self.data.

What does the function / method return if the element is None?

self.data.get(idx).and_then(Option::as_ref)

What does the function / method return if the element is None?

if the element is None I want to load / create it

Yes, but I want to get rid of Option when returning from the get_element

Then what should this method do on out-of-bounds access (i.e. when the index is too large)? Panic? Resize the Vec up to this index (and then create the struct at it, as if it was in bounds)?

I have a 'ensure_prepared' function which fills the vector with None's and the correct number of entries.
(it is reading some stuff from a directory)
The number of entries is known to caller.

    pub fn get_element(&mut self, idx: usize) -> &MyStruct {
        match &mut self.data[idx] {
            Some(existing) => existing,
            opt @ None => {
                *opt = Some(MyStruct);
                opt.as_ref().unwrap()
            }
        }
    }

Or:

fn get_element(&mut self, index: usize) -> &MyStruct
{
    self.data[index].get_or_insert_with(|| MyStruct {})
}
3 Likes

Thanks jongiddy and quinedot

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.