gpt4 book ai didi

rust - 包装 AsyncRead

转载 作者:行者123 更新时间:2023-12-03 11:39:31 33 4
gpt4 key购买 nike

我似乎无法让编译器让我包装 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)
}
}

这似乎应该编译,但编译器提示我没有包含正确的特征绑定(bind),即使 poll_read 可通过 AsyncRead 获得:Playground Link

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

我做错了什么?

最佳答案

selfpoll_read 的签名中:

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

Self 是固定的,意思是 poll_read只能在 Pin<&mut T> 上调用的! self.inner类型为 T这就是编译器找不到 poll_read 的原因在上面。要解决此问题,我们必须以某种方式固定访问该字段。

有一个 whole section rust Pin关于此的文档和 whole crate致力于解决这个问题。

关于rust - 包装 AsyncRead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62032153/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com