【发布时间】:2021-06-28 00:52:10
【问题描述】:
我正在尝试将这些 Readable 实例存储在 Coordinator 结构中
并有一个schedule 方法,该方法选择readables 之一并将其推送到FuturesUnordered 实例(也在Coordinator 中)以供稍后拉取。
问题是:由于生命周期错误而无法编译
use bytes::Bytes;
use futures::prelude::stream::FuturesUnordered;
use std::future::Future;
use std::pin::Pin;
struct Readable {}
impl Readable {
async fn read(&mut self) -> Result<Bytes, ()> {
Err(())
}
}
type Futures = FuturesUnordered<Pin<Box<dyn Future<Output = Result<Bytes, ()>> + Send>>>;
struct Coordinator {
readers: Vec<Readable>,
futures: Futures,
}
impl Coordinator {
fn schedule(&mut self) {
let reader = self.readers.get_mut(0).unwrap();
let f = Box::pin(reader.read());
self.futures.push(f);
}
}
错误
error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
--> src/lib.rs:23:22
|
22 | fn schedule(&mut self) {
| --------- this data with an anonymous lifetime `'_`...
23 | let reader = self.readers.get_mut(0).unwrap();
| ^^^^^^^^^^^^ ...is captured here...
24 | let f = Box::pin(reader.read());
25 | self.futures.push(f);
| - ...and is required to live as long as `'static` here
error: aborting due to previous error
任何人都可以帮助我理解为什么这是一个问题?
具体来说,当我尝试推送到 FuturesUnordered 时,它似乎在抱怨,但我没有看到推送方法的任何生命周期界限:
/// Push a future into the set.
///
/// This method adds the given future to the set. This method will not
/// call [`poll`](core::future::Future::poll) on the submitted future. The caller must
/// ensure that [`FuturesUnordered::poll_next`](Stream::poll_next) is called
/// in order to receive wake-up notifications for the given future.
pub fn push(&self, future: Fut) {...}
我认为它也可能与这个具有自引用的特定结构有关(即:Coordinator::futures 正在引用Coordinator::readers),但我不完全理解这是否相关。
【问题讨论】:
标签: rust lifetime self-reference