What is the difference bewteen || async {} vs. async || {}?

The following code works:

let url = url::Url::parse(url).unwrap();
let (ws_stream, _) = connect_async(url).await.expect("Failed to connect");
let (_, read) = ws_stream.split();
read.for_each( |message| async {})
// ...

But for the follow code

let url = url::Url::parse(url).unwrap();
let (ws_stream, _) = connect_async(url).await.expect("Failed to connect");
let (_, read) = ws_stream.split();
read.for_each(async |message| {})
// ...

I get:

= note: see issue #62290 https://github.com/rust-lang/rust/issues/62290 for more information
= help: add #![feature(async_closure)] to the crate attributes to enable
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

What is the difference bewteen || async {} vs. async || {}? Aren't they all async closure?

|| async {} is the ordinary closure, which returns async block. It is equivalent to the following:

|| {
    return async {
        // code here
    };
}
1 Like

They are pretty similar, there’s discussion in the original RFC about it: https://github.com/rust-lang/rfcs/blob/master/text/2394-async_await.md#async-blocks-vs-async-closures

The current async/await support is basically an “MVP” with a minimal useful subset of the features listed in the RFC, and these were considered too similar to need both right away. Should be fixed in the future.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.