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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
sbw
  • 65
  • 8

1 Answers1

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)
}
fjh
  • 12,121
  • 4
  • 46
  • 46
  • 1
    Why not just `Some(res)`? – DK. Nov 22 '15 at 11:19
  • @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 Nov 22 '15 at 11:45
  • fjh, ok, i will change my return type, thanks a lot! – sbw Nov 22 '15 at 11:53