我正在尝试编写已废止的递归异步方法。这是我的尝试:
use std::future::*;
use std::pin::*;
struct TestRecursiveAsync;
impl TestRecursiveAsync {
pub fn foo(&self, value: u32) -> Pin<Box<(dyn Future<Output = u32>)>> {
let v: Pin<Box<(dyn Future<Output = u32> + 'static)>> = Box::pin(async move {
if value > 0 {
self.foo(value - 100).await
} else {
value
}
});
v
}
}
编译器抱怨此消息(Playground):
Compiling playground v0.0.1 (/playground)
error[E0759]: cannot infer an appropriate lifetime
--> src/lib.rs:8:85
|
7 | pub fn foo(&self, value: u32) -> Pin<Box<(dyn Future<Output = u32>)>> {
| ----- this data with an anonymous lifetime `'_`...
8 | let v: Pin<Box<(dyn Future<Output = u32> + 'static)>> = Box::pin(async move {
| _____________________________________________________________________________________^
9 | | if value > 0 {
10 | | self.foo(value - 100).await
11 | | } else {
12 | | value
13 | | }
14 | | });
| |_________^ ...is captured here, requiring it to live as long as `'static`
|
help: to declare that the trait object captures data from argument `self`, you can add an explicit `'_` lifetime bound
|
7 | pub fn foo(&self, value: u32) -> Pin<Box<(dyn Future<Output = u32> + '_)>> {
| ^^^^
因此,编译器要求&self
的生命周期为'static
,但它具有匿名名称。有办法解决这个问题吗?