I'm trying to get the following to compile:
pub struct Foo {
bars: Option<Vec<String>>,
}
impl Foo {
// Get the bars, memoizing the result.
async fn bars(&mut self) -> &[String] {
if let Some(bars) = &self.bars {
return Ok(bars);
}
self.bars = Some(get_bars().await);
self.bars.as_ref().unwrap()
}
}
// Expensive.
async fn get_bars() -> Vec<String> {
todo!()
}
I have 2 problems:
-
the lifetime of the
if let Some(bars) = &self.bars
borrow is not the same as the&mut self
in the function signature, -
I cannot borrow
self
as mutable inself.bars = Some(get_bars())
becauseself
is still borrowed as immutable 4 lines above.
How can I return the bars
early in the Some
case and continue the function in the None
one?