1

I'm writing a library to learn Rust in a more efficient way. This simplified code shows the compiler error I'm getting. It may be really poorly designed also:

struct Test<'a> {
    pub bar: Option<&'a str>,
}

impl<'a> Test<'a> {
    fn new() -> Test<'a> {
        Test { bar: None }
    }

    fn foobar(&mut self) -> Result<Option<&str>, String> {
        self.bar = match self.bar {
            Some(x) => Some(x),
            None => {
                match a_function() {
                    Ok(x) => Some(x.as_str()),
                    Err(e) => return Err(e),
                }
            }
        };
        Ok(self.bar)
    }
}

fn a_function() -> Result<String, String> {
    Ok("hello_world".to_string())
}
error: `x` does not live long enough
--> src/main.rs:15:35
   |
15 |                     Ok(x) => Some(x.as_str()),
   |                                   ^ does not live long enough
16 |                     Err(e) => return Err(e),
17 |                 }
   |                 - borrowed value only lives until here

I think I understand the issue about x going out of scope too soon, but how can I bind any value to self.bar in the foobar method then?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • As the linked duplicate says, use an owned `String` if you need to own the string. – Shepmaster Jan 06 '17 at 21:52
  • 2
    In short: your x is a local variable of type `String` which life ends at the end of the function. But you are assigning a reference to it to `self` which lives *longer* than the function. That's illegal, of course. Either use a `String` in `Test` or if you're really concerned about performance, maybe [`Cow<'a, str>`](https://doc.rust-lang.org/std/borrow/enum.Cow.html)! – Lukas Kalbertodt Jan 06 '17 at 21:54
  • [A concrete reimplementation](http://play.integer32.com/?gist=8e5bdcf1852cc1136af8f9b79275d9e3&version=stable). – Shepmaster Jan 06 '17 at 22:03
  • Thank you @LukasKalbertodt and @Shepmaster! – on_pwogramè Jan 07 '17 at 01:06

0 Answers0