为什么在使用 AsyncRead 引用字节数组时得到 "no method named `read` found"?

Why do I get "no method named `read` found" when using AsyncRead for a reference to a byte array?

我正在使用 Tokio 通过 TCP 创建 Framed 连接。我正在尝试用内存缓冲区替换测试代码中的 TCP 连接,但我 运行 遇到了下面代码举例说明的问题。

use tokio::{self, io::{AsyncRead, AsyncReadExt}};

#[tokio::main]
async fn main() {
    let data = &[1u8, 2, 3, 4, 5];
    let buf = &mut [0u8; 5];

    let _ = data.read(buf).await;
}

我从编译器得到了这样的响应:

warning: unused import: `AsyncRead`
 --> src/lib.rs:1:24
  |
1 | use tokio::{self, io::{AsyncRead, AsyncReadExt}};
  |                        ^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

error[E0599]: no method named `read` found for type `&[u8; 5]` in the current scope
 --> src/lib.rs:8:18
  |
8 |     let _ = data.read(buf).await;
  |                  ^^^^ method not found in `&[u8; 5]`
  |
  = note: the method `read` exists but the following trait bounds were not satisfied:
          `&[u8; 5] : tokio::io::util::async_read_ext::AsyncReadExt`
          `[u8; 5] : tokio::io::util::async_read_ext::AsyncReadExt`
          `[u8] : tokio::io::util::async_read_ext::AsyncReadExt`

特征未在数组或数组引用上实现,仅在切片上实现:

use tokio::{self, io::AsyncReadExt}; // 0.2.10

#[tokio::main]
async fn main() {
    let data = &[1u8, 2, 3, 4, 5];
    let buf = &mut [0u8; 5];

    let _ = data.as_ref().read(buf).await;

    // Or
    // let _ = (&data[..]).read(buf).await;

    // Or
    // let _ = (data as &[_]).read(buf).await;

    // Or define `data` as a slice originally.
}

另请参阅: