I have a trait:
pub trait HasQuux {
fn quux(&self) -> &Quux;
}
Most structs which implement this have a Quux field, possibly nested, to which they can return a reference. e.g.
pub struct Foo {
...
q: Quux,
...
}
impl HasQuux for Foo {
fn quux(&self) -> &Quux {
&self.q
}
}
How can I implement HasQuux for structs which must calculate their Quux?
This implementation:
impl HasQuux for Bar {
fn quux(&self) -> &Quux {
let q: Quux = self.calc_quux();
&q
}
}
causes:
error[E0515]: cannot return reference to local variable `q`
--> /home/fadedbee/test.rs:38:3
|
38 | &q
| ^^ returns a reference to data owned by the current function
I am keen for quux() to return a reference, as 99% of structs implementing HasQuux have a Quux field.
I understand why this isn't possible.
Can I create a temporary Quux whose lifetime matches the lifetime of Bar and return a reference to that?
Or is there a better solution?