Cannot borrow `*x` as mutable more than once at a time

Viewed 67

Please take a look at my code and suggest a possible fix:

use std::future::Future;

pub async fn bar() {
    let mut x = 0u8;
    foo(&mut x, |x| baz(x)).await;
}

pub async fn baz(x: &mut u8) {
    *x += 1;
}

pub async fn foo<'a, F, T>(x: &'a mut u8, f: F)
where
    F: Fn(&'a mut u8) -> T,
    T: Future<Output = ()> + 'a,
{
    loop {
        f(x).await;
    }
}

Why does x remain borrowed after await? What is a proper fix?

1 Answers

It seems I have found a way to solve the problem with non-generic future type:

use std::future::Future;
use std::pin::Pin;

pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;

pub async fn bar() {
    let mut x = 0u8;
    foo(&mut x, baz).await;
}

pub fn baz(x: &mut u8) -> BoxFuture<()> {
    Box::pin(async move {
        baz2(x).await
    })
}

pub async fn baz2(x: &mut u8) {
    *x += 1;
}

pub async fn foo<F>(x: &mut u8, f: F)
where
    F: Fn(&mut u8) -> BoxFuture<()>,
{
    loop {
        f(x).await;
    }
}
Related