引言
在 2023 年 12 月,一件小奇迹发生了:Traits 中的 async fn
正式发布。
自 Rust 1.39 版本起,我们已经拥有了独立的异步函数:
pub async fn read_hosts() -> eyre::Result<Vec<u8>> {
// 等等
}
以及在 impl
块中的异步函数:
impl HostReader {
pub async fn read_hosts(&self) -> eyre::Result<Vec<u8>> {
// 等等
}
}
但我们仍然无法在 Traits 中使用异步函数:
use std::io;
trait AsyncRead {
async fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
}
当尝试编译时,会出现如下错误:
❯ cargo +1.74.0 check --quiet
error[E0706]: functions in traits cannot be declared `async`
--> src/main.rs:9:5
|
9 | async fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
| -----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| `async` because of this
|
= note: `async` trait functions are not currently supported
= note: consider using the `async-trait` crate: https://crates.io/crates/async-trait
= note: see issue #91611 <https://github.com/rust-lang/rust/issues/91611> for more information
For more information about this error, try `rustc --explain E0706`.
error: could not compile `sansioex` (bin "sansioex") due to previous error