Rust Can';t调用tokio::fs::File上的poll_read
我有一个包含Rust Can';t调用tokio::fs::File上的poll_read,rust,rust-tokio,tokio,Rust,Rust Tokio,Tokio,我有一个包含Filestruct的结构,我希望这个结构实现AsyncReadtrait,以便在代码的其他部分可以使用它来代替File: struct TwoWayFile<'a> { reader: &'a File, } impl<'a> AsyncRead for TwoWayFile<'a> { fn poll_read( mut self: Pin<&mut Self>, c
File
struct的结构,我希望这个结构实现AsyncRead
trait,以便在代码的其他部分可以使用它来代替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)
}
}
这里少了什么?为什么我不能调用已为
文件定义的方法?您的问题可能是轮询读取
方法是在Pin
上实现的,而不是在&self
上实现的。这意味着您只能在固定的可变引用上调用它,而不能在普通引用上调用它
您可以使用Box::pin将引用固定在堆上,或者使用pin\mut将引用固定在“异步堆栈”上代码>宏,然后应该能够调用该方法。我将结构中对文件的引用替换为一个值,并在Pin
上调用poll\u read
,它成功了!谢谢
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`