Rust: Unhelpful "cannot infer type" error for ? in async block with unclear Result Err type

Created on 13 Oct 2020  路  4Comments  路  Source: rust-lang/rust

Minimal reproduction:

fn may_error() -> Result<(), ()> { unimplemented!() }

fn main() {
    async {
        may_error()?;
        Ok(())
    };
}

1.47.0 gives the following error:

error[E0282]: type annotations needed
 --> src/main.rs:5:9
  |
5 |         may_error()?;
  |         ^^^^^^^^^^^^ cannot infer type

Nightly gives a marginally more useful error:

error[E0282]: type annotations needed
 --> src/main.rs:5:20
  |
5 |         may_error()?;
  |                    ^ cannot infer type

I would expect an explanation of what type precisely couldn't be inferred, along with a pointer to the containing async block as the thing whose type couldn't be inferred.

rustc --version --verbose (for 1.47.0):

rustc 1.47.0 (18bf6b4f0 2020-10-07)
binary: rustc
commit-hash: 18bf6b4f01a6feaf7259ba7cdae58031af1b7b39
commit-date: 2020-10-07
host: x86_64-unknown-linux-gnu
release: 1.47.0
LLVM version: 11.0

rustc --version --verbose (for nightly):

rustc 1.49.0-nightly (c71248b70 2020-10-11)
binary: rustc
commit-hash: c71248b70870960af9993de4f31d3cba9bbce7e8
commit-date: 2020-10-11
host: x86_64-unknown-linux-gnu
release: 1.49.0-nightly
LLVM version: 11.0


A-async-await A-diagnostics A-inference AsyncAwait-Triaged C-bug D-terse E-help-wanted E-medium E-mentor T-compiler

Most helpful comment

I'm willing to take a shot at this.

@rustbot claim

All 4 comments

Turning this into a closure gives a more helpful error:

error[E0282]: type annotations needed for the closure `fn() -> std::result::Result<(), _>`
 --> src/lib.rs:5:9
  |
5 |         may_error()?;
  |         ^^^^^^^^^^^^ cannot infer type
  |
help: give this closure an explicit return type without `_` placeholders
  |
4 |     let g = || -> std::result::Result<(), _> {
  |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

@jyn514 Yeah, I found that several different code changes led to better errors.

I'd guess part of the issue is that there's no stable way to add a type annotation directly to an async block.

We should update the part of the code that emits the help text for closures (search for give this closure an explicit return type) to fall back to another error message for async blocks.

Maybe we can still print the type as in the closure case, just to point to the _ as the part we can't infer? It might take some experimenting to get the presentation right.

I'm willing to take a shot at this.

@rustbot claim

Was this page helpful?
0 / 5 - 0 ratings