AsyncRead trait bound not recognized

To my understanding the following code is correct, nonetheless it doesn't compile neither in stable nor in nightly. Why is that, what is wrong with it?

use futures::AsyncRead;
use std::{
   io::Result as IoResult,
   pin::Pin,
   task::{Context, Poll},
};

struct NewType<T: AsyncRead>(T);

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

Error

   Compiling playground v0.0.1 (/playground)
error[E0599]: no method named `poll_read` found for type parameter `T` in the current scope
  --> src/lib.rs:14:14
   |
14 |       self.0.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

error: aborting due to previous error

For more information about this error, try `rustc --explain E0599`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

Playground Demo

The quick answer is that your type isn’t right for calling the poll function. When you call self.0 you have type T. To call poll_read you need Pin<&mut T>. The easiest way to make that work is to use the pin_project crate. It handles pinning an item in the struct when the struct is pinned.

Playground Link

1 Like

That makes sense, it works now.
The error message was kinda confusing because it doesn't mention anything about the type it was trying to match against when verifying the trait bounds

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.