Return slice of struct from function

I am stuck with either my objects are owned or my struct is owned.
I have the following code:

    struct Person {


    fn scan_persons<'a>() -> &'a [Person] {
        let mut v: Vec<Person> = Vec::new();
        let t = Person {}; <-- owned by function. what do I do?

        v.as_slice()  <-- fails here

Return the Vec<Person> instead of the slice

Still the owned by the function problem.

Seems to work fine, so the issue must be somewhere outside of provided code.

1 Like

Slices (all borrows in general) are temporary views of data that has to have a more permanent storage somewhere else.

You can’t borrow a temporary local variable and run away with a reference to it. The storage will be destroyed before the end of the function, so the view into that storage can’t be returned beyond that function.


To expand on the misconception here:

let t = Person {}; <-- owned by function. what do I do?

Once you perform v.push(t), t is no longer owned by the function. It has been moved into the Vec.

Therefore, you should encounter no issue returning the Vec.


You can remove the lifetime parameter, since it isn’t used.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.