将AsyncRead包装起来

4

我似乎无法让编译器允许我包装Tokio的AsyncRead:

use std::io::Result;
use core::pin::Pin;
use core::task::{Context, Poll};

use tokio::io::AsyncRead;

struct Wrapper<T: AsyncRead>{
    inner: T
}

impl<T: AsyncRead> AsyncRead for Wrapper<T> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8]
    ) -> Poll<Result<usize>> {
        self.inner.poll_read(cx, buf)
    }
}

似乎这段代码应该能编译通过,但编译器报错说我没有包含正确的特性绑定,尽管 poll_read 已经通过 AsyncRead 可用。链接:Playground 链接
error[E0599]: no method named `poll_read` found for type parameter `T` in the current scope
  --> src/lib.rs:17:20
   |
17 |         self.inner.poll_read(cx, buf)
   |                    ^^^^^^^^^ method not found in `T`
   |
   = help: items from traits can only be used if the type parameter is bounded by the trait

我做错了什么?

1个回答

3

看一下 poll_read 签名中的 self:

fn poll_read(
    self: Pin<&mut Self>, // Self is pinned!
    cx: &mut Context,
    buf: &mut [u8]
) -> Poll<Result<usize>>

自身被固定,意味着只能在>上调用!的类型为,这就是编译器找不到的原因。为了解决这个问题,我们必须以某种方式获得对该字段的固定访问权限。
Rust的文档有一个整个部分专门介绍这个问题,还有一个整个crate专门解决这个问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接