Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

rust - What is the difference between `|_| async move {}` and `async move |_| {}`

Let's consider the following examples:

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"

I'm asking about the expression |x| async move {} instead of async move |x| {}. The latter is more obvious, but it runs into the compilation error:

error[E0658]: async closures are unstable

Then I wonder, what is the difference between async move || {} and || async move {}. They both seems to be closures for using the move keyword.

$ rustc --version
rustc 1.39.0 (4560ea788 2019-11-04)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One is the async block (a closure with async block as its body to be precise), while the other is async closure. Per async/await RFC:

async || closures

In addition to functions, async can also be applied to closures. Like an async function, an async closure has a return type of impl Future<Output = T>, rather than T.

On the other hand:

async blocks

You can create a future directly as an expression using an async block. This form is almost equivalent to an immediately-invoked async closure:

 async { /* body */ }

 // is equivalent to

 (async || { /* body */ })()

except that control-flow constructs like return, break and continue are not allowed within body.

The move keyword here is to denote that the async closure and block are to capture ownership of the variables they close over.

And apparently, async closure is still deemed to be unstable. It has this tracking issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...