0

I want to write a function that receives a &str argument and returns Option<&str>. I wrote this:

fn f(text: &str) -> Option<&str> {
    if // some condition {
        return None;
    }

    let mut res = String::new();
    // write something into res.

    // return res
    Some(&res[..])
}

but I get an error:

res does not live long enough.

What is the best solution to fix this?

0

1 Answer 1

6

You cannot return a &str that points into a local String variable. Doing that would mean that you just returned a dangling pointer, as the String (res, in your code) is destroyed when the function returns.

The best way to fix your problem is probably to return a Option<String>, i.e. return the owned string instead of a string slice. Adapting your code, you might end up with something like this:

fn f(text: &str) -> Option<String> {
    if // some condition {
        return None;
    }

    let mut res = String::new();
    // write something into res.

    Some(res)
}
Sign up to request clarification or add additional context in comments.

3 Comments

Why not just Some(res)?
@DK. Yeah, that made no sense. I read the [..] as pseudo-code for "some unspecified slice into that string", instead of its literal meaning for some reason. Thanks!
fjh, ok, i will change my return type, thanks a lot!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.