Understanding an unexpected async-fn borrow checker error

⚓ rust    📅 2025-06-05    👤 surdeus    👁️ 1      

surdeus

The following code results in this error:

error[E0502]: cannot borrow *self as mutable because it is also borrowed as immutable

struct Cache {
    data: Option<Data>,
}

struct Data {}

impl Cache {
    async fn get(&mut self) -> &Data {
        loop {
            if let Some(data) = &self.data {
                return data;
            }

            self.update().await;
        }
    }

    async fn update(&mut self) {
        todo!("update `self.data` if possible")
    }
}

Replacing Some(data) = &self.data with Some(ref data) = self.data makes the code compile!

Why does the original not work? (I guess it relates to what the scope of the immutable borrow is assumed to be, namely across the await point, even though it logically should not be?)

And why exactly does changing to ref help?

Please point me to documentation that explains this, if possible.

Thanks!

2 posts - 2 participants

Read full topic

🏷️ rust_feed