In the main method, I first create an owned builder which is then mutably borrowed by the number function which tries to return a reference to itself:
struct Builder {
string: Option<String>,
number: Option<usize>,
}
impl Builder {
fn default() -> Builder {
Builder {
string: None,
number: None,
}
}
fn number(&mut self, n: usize) -> &mut Self {
self.number = Some(n);
&mut self
}
fn to_string(&self) -> &'static str {
"tte"
}
}
// Do not modify this function.
fn main() {
let _test = Builder::default().number(456).to_string();
}
I don't see why the borrowed value wouldn't "live long enough":
error[E0597]: `self` does not live long enough
--> src/main.rs:16:14
|
16 | &mut self
| ^^^^ borrowed value does not live long enough
17 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 14:5...
--> src/main.rs:14:5
|
14 | / fn number(&mut self, n: usize) -> &mut Self {
15 | | self.number = Some(n);
16 | | &mut self
17 | | }
| |_____^
What is exactly going on here and how do I fix it? I tried to add lifetimes to the number
method but that seems to be the wrong approach.