试图编写递归流,其中每个流从他的父流轮询,当轮询准备好值时,它使自己的异步抓取器处理父响应,但我不知道如何存储由抓取器给定的当前future ,编译器抱怨生存期,直到我try 使用自由的异步函数(未绑定到 struct ).这里有不完整的示例,但它说明了编译器错误(在Stream实现中注释了两行):
struct AsyncFetcher {}
impl AsyncFetcher {
async fn fetch(&self, request: String) -> String {
format!("Response({request})")
}
}
enum State {
PendingParent,
ToProcess(Option<String>),
Processing(Pin<Box<dyn Future<Output = String>>>)
}
struct RecStream {
parent: Option<Pin<Box<dyn Stream<Item = String>>>>,
state: State,
fetcher: AsyncFetcher,
}
impl RecStream {
fn new(parent: Pin<Box<dyn Stream<Item = String>>>, fetcher: AsyncFetcher) -> Self {
Self {
parent: Some(parent),
state: State::PendingParent,
fetcher: fetcher,
}
}
fn with_result(result: String, fetcher: AsyncFetcher) -> Self {
Self {
parent: None,
state: State::ToProcess(Some(result)),
fetcher: fetcher,
}
}
}
impl Stream for RecStream {
type Item = String;
fn poll_next(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<Option<Self::Item>> {
let ref_mut = self.get_mut();
let future = ref_mut.fetcher.fetch("Some str".to_string()).boxed();
// let future = free_fut().boxed(); // - THIS WORKS
ref_mut.state = State::Processing(future); // Getting error 'lifetime may not live long enough'
return Poll::Pending;
}
}
async fn free_fut() -> String {
"Free string".to_string()
}