I'm trying to implement a simple builder but struggling with lifetimes. The following is giving error: borrowed value does not live long enough
. This question seems similar. If I store t
in a mutable variable and then call s
and finalize it works, but I want to get the one liner to work. What am I doing wrong?
struct Type<'a> {
s: &'a String,
}
struct TypeBuilder {
s: String,
}
impl TypeBuilder {
fn new() -> TypeBuilder {
TypeBuilder { s: "".to_string() }
}
fn s(&mut self, s: String) -> &mut TypeBuilder {
self.s = s;
self
}
fn finalize(&self) -> Type {
Type { s: &self.s }
}
}
fn main() {
let t = TypeBuilder::new()
.s("a".to_string())
.finalize();
println!("string: {}", t.s);
}