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?