Rust 异步函数可以在不导入 Future 特性的情况下工作吗?
Can a Rust async function work without importing the Future trait?
在下面的代码中,我没有导入 Future
特征:
async fn hello_world() {
println!("hello, world!");
}
fn main() {
let future = hello_world();
}
但它仍然可以编译。但是它不会打印任何东西。
根据why async fn in traits are hard:
impl MyDatabase {
async fn get_user(&self) -> User {
...
}
}
This would get desugared to something similar to:
impl MyDatabase {
fn get_user(&self) -> impl Future<Output = User> + '_ {
...
}
}
如果没有导入 Future
特征,如何进行脱糖?更重要的是,为什么 Future
trait 没有在 Rust 本身中定义,而是在 crate 中定义?
How can this desugar be done if no Future
trait is imported?
编译器脱糖到完全限定路径:core::future::Future
。
why is the Future
trait not defined in Rust itself, but instead is in a crate?
它在标准库中:std::future::Future
。 Rust API 文档有搜索功能;我鼓励你熟悉它。
Future
trait 是 在 futures crate 添加到标准库之前定义的,很像 Stream
trait。它们现在都存在于标准库中。
在下面的代码中,我没有导入 Future
特征:
async fn hello_world() {
println!("hello, world!");
}
fn main() {
let future = hello_world();
}
但它仍然可以编译。但是它不会打印任何东西。
根据why async fn in traits are hard:
impl MyDatabase { async fn get_user(&self) -> User { ... } }
This would get desugared to something similar to:
impl MyDatabase { fn get_user(&self) -> impl Future<Output = User> + '_ { ... } }
如果没有导入 Future
特征,如何进行脱糖?更重要的是,为什么 Future
trait 没有在 Rust 本身中定义,而是在 crate 中定义?
How can this desugar be done if no
Future
trait is imported?
编译器脱糖到完全限定路径:core::future::Future
。
why is the
Future
trait not defined in Rust itself, but instead is in a crate?
它在标准库中:std::future::Future
。 Rust API 文档有搜索功能;我鼓励你熟悉它。
Future
trait 是 在 futures crate 添加到标准库之前定义的,很像 Stream
trait。它们现在都存在于标准库中。