Rust 官方博客 - 宣布在 traits 中支持 async fn
和返回位置上的 impl Trait
Rust 官方博客在最新的文章中宣布了一项重要进展:支持在 traits 中使用 async fn
和返回位置上的 impl Trait
。这一功能将在 Rust 1.75 版本中正式发布,该 stable 版本将于下周发布。
下面是一个混合 async fn
和 -> impl Trait
的例子:
trait HttpService: Send {
fn fetch(&self, url: Url)
-> impl Future<Output = HtmlBody> + Send;
}
impl HttpService for MyService {
async fn fetch(&self, url: Url) -> HtmlBody {
// This works, as long as `do_fetch(): Send`!
self.client.do_fetch(url).await.into_body()
}
}
文章还探讨了这些功能的一些限制和未来的改进计划。例如,目前还不鼓励在 pub traits 中使用 -> impl Trait
还不被鼓励,因为用户无法对返回类型添加额外的约束。此外,在 pub traits 中使用 async fn
也存在类似的限制。
Announcing async fn
and return-position