没有为实现“Future”的类型找到名为“poll”的方法

No method named `poll` found for a type that implements `Future`

我正在尝试创建一个允许某人调用 .shutdown() 的结构,这将解决未来(否则未决)。它只能被调用一次。在 Future 特性的实现中,我收到一个错误,指出 poll 未定义,尽管它存在于 the documentation 中(在 impl Future 下)。

虽然我使用 std::future::Future 作为 impl,但我尝试添加 use futures::prelude::*,这会将预览特性纳入范围。 RLS 和 rustc 都告诉我导入未使用,所以这不是问题。

请注意,我没有使用一个简单的布尔标志,因为我打算让它能够从任何线程调用——这是一个与此处无关的实现细节。

use futures::channel::oneshot; // futures-preview@0.3.0-alpha.17
use std::{
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};

pub struct ShutdownHandle {
    sender: oneshot::Sender<()>,
    receiver: oneshot::Receiver<()>,
}

impl ShutdownHandle {
    pub fn new() -> Self {
        let (sender, receiver) = oneshot::channel();
        Self { sender, receiver }
    }

    pub fn shutdown(self) -> Result<(), ()> {
        self.sender.send(())
    }
}

impl Future for ShutdownHandle {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        self.receiver.poll(&mut cx).map(|_| ())
    }
}

fn main() {
    let runner = ShutdownHandle::new();
    assert!(runner.shutdown().is_ok());
}

我收到以下错误:

error[E0599]: no method named `poll` found for type `futures_channel::oneshot::Receiver<()>` in the current scope
  --> src/main.rs:28:23
   |
28 |         self.receiver.poll(&mut cx).map(|_| ())
   |                       ^^^^

我错过了什么?当然有一些方法可以 "pass through" 投票。我每晚都在使用 (2019-07-18)。

没错,Receiver没有实现Future;只有 Pin<&mut Receiver> 可以。您需要投影 从您的类型到字段的固定。

当底层类型可能无法实现时 Unpin

impl Future for ShutdownHandle {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        // I copied this code from Stack Overflow without reading the text that
        // told me how to verify that this code uses `unsafe` correctly.
        unsafe { self.map_unchecked_mut(|s| &mut s.receiver) }.poll(cx).map(|_| ())
    }
}

您必须阅读 pin module 以彻底理解此处使用 unsafe 的要求。

更清洁的解决方案

我喜欢使用辅助库,例如pin_project,来处理更复杂的投影类型:

#[unsafe_project(Unpin)]
pub struct ShutdownHandle {
    #[pin]
    sender: oneshot::Sender<()>,
    #[pin]
    receiver: oneshot::Receiver<()>,
}

impl Future for ShutdownHandle {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        let this = self.project();
        this.receiver.poll(cx).map(|_| ())
    }
}

当基础类型实现时Unpin

that the futures-preview crate provides FutureExt::poll_unpin. This method takes a mutable reference to a type that implements Unpin 并用它创建一个全新的 Pin

由于 oneshot::Receiver 确实实现了 Unpin,因此可以在此处使用:

impl Future for ShutdownHandle {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        self.receiver.poll_unpin(cx).map(|_| ())
    }
}

另见