Skip to content

Unify closure and block #2824

Closed
Closed
@CGQAQ

Description

@CGQAQ

Motivation: make Rust more explicit , consistent and sovle this issue

The idea is basically like every block could written as closure so can specify return type and parameters(will explain in detail later)

Async block return type infer issue

async fn a() -> Result<(), reqwest::Error> {Ok(())}
async fn b() -> Result<(), std::io::Error> {Ok(())}
fn c() {
    async {
        a().await?;
        b().await?;
        Ok(())
    };
}

This will raise compilation error:

error[E0282]: type annotations needed --> src/x.rs:6:9
  |
6 |         a().await?;
  |         ^^^^^^^^^^ cannot infer type

error: aborting due to previous error

For more information about this error, try `rustc --explain E0282`.
error: could not compile `v2yay`.

with my proposal, will become like this:

fn c() {
    async || -> Result<(), impl std::error::Error> {
        a().await?;
        b().await?;
        Ok(())
    };
}

Now you would think, what's the point about ||, it's the second use case about my proposal: make Rust a more expilict language.

In rust, almost every block could return a value, and could use some variables outset of itself

let a: Vec<u32> = Vec::new();
let _ = if true {
    a
} else {
    Vec::new()
}
println!("{:?}", a);
33 |     println!("{:?}", a);
   |                      ^ value borrowed here after move

With my proposal, every block is just same as closure, you can do this if you want instead of change a to &a everywhere:

let _ = if true |&a| -> .... {
    //                  ^ specify return type explicitly
    //            ^ specify borrow explicitly, others will move by default, all variables between || , just a new temp variable that shadows original
    //     maybe add some feature so that borrow by default, specify move explicity, that will be more convenient
} else { ... }

Of cause all is optional, just specify if you need

// same thing with while, loop ...
while true ||->xxx{}
loop ||->{}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions