我有一个封装了File
结构的结构,并且我希望这个结构实现AsyncRead
特性,以便可以在代码的其他部分中代替File
来使用它:
struct TwoWayFile<'a> {
reader: &'a File,
}
impl<'a> AsyncRead for TwoWayFile<'a> {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
self.reader.poll_read(cx, buf)
}
}
根据文档,
tokio::fs::File
已经实现了tokio::io::AsyncRead
,但是编译器说的恰恰相反:error[E0599]: no method named `poll_read` found for reference `&'a tokio::fs::file::File` in the current scope
--> src/main.rs:44:21
|
44 | self.reader.poll_read(cx, buf)
| ^^^^^^^^^ method not found in `&'a tokio::fs::file::File`
这里缺少什么?为什么我不能调用已经为
File
定义的方法?
最佳答案
您的问题很可能是poll_read
方法是在Pin<&mut Self>
上实现的,而不是在&self
上实现的。这意味着您只能在固定的可变引用上调用它,而不能在普通引用上调用它。
您可以使用Box::pin
将引用固定在堆上,或者使用pin_mut!
宏将引用固定在“异步堆栈”上,然后应该可以调用该方法。
关于rust - 无法在tokio::fs::File上调用poll_read,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60920804/