让我们看下以下例子:
main.rs
use futures::executor::block_on;
use futures::future::{FutureExt, TryFutureExt};
async fn fut1() -> Result<String, u32> {
Ok("ok".to_string())
}
fn main() {
println!("Hello, world!");
match block_on(fut1().and_then(|x| async move { Ok(format!("{} is \"ok\"", x)) })) {
Ok(s) => println!("{}", s),
Err(u) => println!("{}", u)
};
}
Cargo.toml
[dependencies]
futures = "^0.3"
我问的是表达式|x| async move {}
而不是async move |x| {}
。后者更明显,但会遇到编译错误:
error[E0658]: async closures are unstable
我想知道 async move || {}
和 || async move {}
之间有什么区别。它们似乎都是使用 move
关键字的闭包。
$ rustc --version
rustc 1.39.0 (4560ea788 2019-11-04)
async move || ...
会将变量从封闭块移动到闭包中,而|| async move {...}
则会将变量从闭包中移动到异步块中。如果你想将它们从封闭块移动到异步块中,我认为现在需要使用move || async move {...}
。 - Sven Marnachglobal_string
的引用,但它只是移动了。 - Ömer Erdenasync
块中的代码只有在我await
未来时才会启动,对吗? - Mr.Wang from Next Door