我在 rust 迹斑斑的操场上做练习,而我却执着于实现一个 struct 的future .以下是该任务的外观:
//Provide a Future trait implementation, transparently polling the inner_future,
// and printing its execution time in nanoseconds once it's ready.
// Using Fut: Unpin trait bound (or similar) is not allowed.
struct Measurable<Fut> {
inner_future: Fut,
started_at: Instant,
}
这项任务似乎很明确.我们需要在Future周围创建一个包装器,并打印它的执行时间.然而,目前还不清楚FUT是什么.我假设这是一个future ,并起草了以下代码:
use futures::executor::block_on;
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
time::Duration,
time::Instant,
};
#[derive(Debug)]
struct Measurable<Fut> {
inner_future: Fut,
started_at: Instant,
}
impl<Fut> Measurable<Fut> {
fn new(inner_future: Fut) -> Self {
MeasurableFuture {
inner_future,
started_at: Instant::now(),
}
}
}
impl<Fut: Future> Future for Measurable<Fut> {
type Output = Fut::Output;
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
// move occurs because value has type `Fut`, which does not implement the `Copy` trait
let Res=Poll::Ready(self.ner_Future);
match res {
// syntax says that 'result' is a Fut, should i return Fut or Fut::Output?
Poll::Ready(result) => {
println!(
"Completed: {:?}",
Instant::now().checked_duration_since(self.started_at)
);
result
// Poll::Pending
}
Poll::Pending => Poll::Pending,
}
}
}
async fn hello_world() {
std::thread::sleep(Duration::from_secs(1));
println!("hello, world!");
}
fn main() {
let w = Measurable::new(hello_world());
let result = block_on(w);
println!("{:?}", result);
}
所以有两个问题:
-
之所以发生移动,是因为值的类型为
Fut
,该类型不实现Copy
特征Res=Poll::Ready(self.ner_Future);
-
我不知道当任务完成后我应该返回什么
问题是,我如何正确地实现这种情况下的民意测验,以及我应该返回什么?也许我误解了这项任务.