【问题标题】:Implement Future trait based on future available inside the struct根据结构内部可用的未来实现未来特征
【发布时间】:2022-11-27 08:26:28
【问题描述】:

我正在尝试创建一个 DelayedValue 未来,它在经过一段时间后解析为一个值。为此,我只是想将 Sleep 包装箱中的 Sleep 包装起来。但是我收到与Pin 相关的错误,无论我做什么,我似乎都无法在底层Sleep 成员上调用poll 方法。

作为参考,这里有一个完整的程序,它无法编译,但应该说明我想要什么:

use futures::task::{Context, Poll};
use futures::Future;
use std::pin::Pin;
use tokio::time::{sleep, Sleep, Duration};

struct DelayedValue<T> {
    value: T,
    sleep: Sleep,
}

impl<T> Future for DelayedValue<T> {
    type Output = T;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match &mut self.sleep.poll(cx) {
            Poll::Ready(()) => Poll::Ready(self.value),
            x => x,
        }
    }
}

#[tokio::main]
async fn main() {
    let dv = DelayedValue {
        value: 10_u8,
        sleep: sleep(Duration::from_millis(5000)),
    };

    println!("waiting for delayed value");
    
    let v = dv.await;
    println!("delayed value: {}", v);
}

还有游乐场链接:https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d573d8dcbbef5c99314d98cacc3d6c92

【问题讨论】:

    标签: rust async-await rust-tokio rust-futures rust-async-std


    【解决方案1】:

    最简单的方法是使用pin-projectpin-project-lite

    pin_project_lite::pin_project! {
        struct DelayedValue<T> {
            value: Option<T>,
            #[pin]
            sleep: Sleep,
        }
    }
    
    impl<T> Future for DelayedValue<T> {
        type Output = T;
    
        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
            let this = self.project();
            match this.sleep.poll(cx) {
                Poll::Ready(()) => Poll::Ready(this.value.take().unwrap()),
                Poll::Pending => Poll::Pending,
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 2021-10-07
      • 2021-01-25
      相关资源
      最近更新 更多