Hi, I have this snippet of code:
pub struct SomeBuilder<'a>{
pub arg1: &'a str
}
impl<'a> SomeBuilder<'a>{
pub fn new(arg1: &'a str) -> SomeBuilder<'a>{
SomeBuilder{
arg1
}
}
pub fn set_arg(&mut self, arg1: &'a str){
self.arg1 = arg1;
}
pub fn build(self) -> String{
self.arg1.to_string()
}
}
fn setter(mut builder: SomeBuilder) -> String{
let str1 = String::from("asdad");
builder.set_arg(str1.as_str());
builder.build()
}
fn main(){
let builder = SomeBuilder::new("Hello");
setter(builder);
}
This is just for exemplification as my real usecase is longer and more complex, but essentially the compiler complains about the lifetime of "str1":
23 | fn setter(mut builder: SomeBuilder) -> String{
| ----------- has type `SomeBuilder<'1>`
24 | let str1 = String::from("asdad");
| ---- binding `str1` declared here
25 | builder.set_arg(str1.as_str());
| ----------------^^^^----------
| | |
| | borrowed value does not live long enough
| argument requires that `str1` is borrowed for `'1`
26 | builder.build()
27 | }
| - `str1` dropped here while still borrowed
From my point of view, this should be perfectly valid, the Builder is constructed on the main function, passed by value to the "setter" function, which then resets the argument with a local scope variable. Finally the builder is destroyed at the end of that scope, which should make the code valid.
Instead, the compiler acts as the builder was not destroyed and it was passed back to the main function. Maybe there is a mechanism that I am not aware of, to coerce the lifetime of the builder data to be the same as the function scope.