I am trying to conditionally update an argument to a function:
struct A {
foo: i32,
bar: i32,
}
impl A {
fn foobar<'a>(&'a self) {
let a;
if true { // something more complex obviously
let x = A {
foo: self.foo,
bar: self.bar,
};
a = &x;
} else {
a = self;
}
println!("{} {}", a.foo, a.bar);
}
}
Here, the function foobar
receives an argument of type &A
. Depending on some condition I want to replace this argument with another value of type &A
.
I do understand why the above code results in the error 'x' does not live long enough
. My question is whether there is a pattern to conditionally update the value of the argument a
without requiring it to be mutable? Is there maybe a way to forcefully extend the lifetime of x
?