rustownershipownership-semantics

vector of string slices goes out of scope but original string remains, why is checker saying there is an error?


Beginner at rust here. I understand why the code below has an error. test(x) creates y then returns a value that references the &str owned by y. y is destroyed as it goes out of scope so it can't do that.

Here's my issue the thing is the &str owned by y is actually a slice of x that has NOT went out of scope yet... so technically the reference should still work.

enum TestThing<'a> {
    Blah(&'a str)
}

fn test(x: &str) -> Vec<TestThing> {
    let y = x.split(" ").collect::<Vec<&str>>();
    parse(&y)
}

fn parse<'a>(x: &'a Vec<&str>) -> Vec<TestThing<'a>> {
    let mut result: Vec<TestThing> = vec![];
    for v in x {
        result.push(TestThing::Blah(v));
    }
    result
}

Is the checker just being over-zealous here? Is there a method around this? Am I missing something? Is this just something to do with split? I also tried cloning v, and that didn't work either.


Solution

  • Move the lifetime here: x: &'a Vec<&str> -> x: &Vec<&'a str>.

    P.S. Using a slice (&[&'a str]) would be better, since it's smaller and more flexible, see Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?. Some kind of impl Iterator or impl IntoIterator would be even more flexible.