不能一次多次借用"*x"作为可变项



请查看我的代码,并提出一个可能的修复方案:

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;
}
}

为什么x在await之后仍然被借用?什么是正确的解决方案?

我似乎找到了一种解决非通用未来类型问题的方法:

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;
}
}

最新更新