Skip to content

Error "cannot infer type" when using '?' in async block + bad diagnostic #63502

Open

Description

@rosalyntg

This seems related to #42424, except I don't see an obvious workaround like in #42424.

#![feature(async_await)]

use std::io::Error;

fn make_unit() -> Result<(), Error> { 
    Ok(())
}

fn main() {
    let fut = async {
        make_unit()?;
        
        Ok(())
    };
}

Fails with the error

error[E0282]: type annotations needed for `impl std::future::Future`
  --> src/main.rs:11:9
   |
10 |     let fut = async {
   |         --- consider giving `fut` the explicit type `impl std::future::Future`, with the type parameters specified
11 |         make_unit()?;
   |         ^^^^^^^^^^^^ cannot infer type

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=ea7e5f7b6e1637f6a39aee0b8209c99e

First of all, it seems like this shouldn't be an error--it should be able to deduce that the return type is Result<(), io::Error>, but also the diagnostic does not work. If you try to add impl std::future::Future<Output=Result<(), Error>> as a type annotation, it also fails to compile because impl Trait is only allowed as return types and argument types.

Playground link

Activity

  1. added
    A-diagnosticsArea: Messages for errors, warnings, and lints
    C-bugCategory: This is a bug.
    T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.
    requires-nightlyThis issue requires a nightly compiler in some way. When possible, use a F-* label instead.
    on Aug 12, 2019
  2. added
    AsyncAwait-TriagedAsync-await issues that have been triaged during a working group meeting.
    on Aug 12, 2019
  3. estebank commented on Aug 12, 2019

    @estebank
    Contributor

    Opened #63504 for the incorrect suggestion. For the main issue, ? interacts in non-obvious ways with type inference because it does implicit conversion. In this case, because fut doesn't explicitly constraint what the expected type is, rustc doesn't know what Result<(), std::io:Error> should be converted to.

    There are other similar tickets filed about these kind of type inference issues: #49391, #38508, #46333, #46680, #48089, #61152, #58517 and #63082.

    (larger work around ? tracked in #31436)

  4. cramertj commented on Aug 13, 2019

    @cramertj
    Member

    I don't see an obvious workaround

    The workaround is this:

    use std::io::Error;
    
    fn make_unit() -> Result<(), Error> { 
        Ok(())
    }
    
    fn main() {
        let fut = async {
            make_unit()?;
            
            Ok::<(), Error>(())
        };
    }
  5. added a commit that references this issue on Aug 14, 2019
  6. nikomatsakis commented on Aug 28, 2019

    @nikomatsakis
    Contributor

    Discussing as part of a "triage effort". A few notes:

    • This isn't (necessarily) an inference failure: the original code snippet is somewhat underspecified, in that the return type of the async block can be any error type E that the Error value can be Into'd into.
    • What's needed is probably (a) a syntax to conveniently specify the error type and (b) a diagnostic that suggests said syntax.

    We lack a syntax. So maybe we can give a better diagnostic that at least hints at the solution. Or maybe an extended error code description.

  7. estebank commented on Aug 28, 2019

    @estebank
    Contributor

    For this case, we probably could suggest a temporary local binding with an explicit type:

        let fut = async {
            let x: Result<_, Error> = make_unit();
            x?;
            Ok(())
        };
    

    As for the syntax, we could borrow the closure syntax and allow something like async -> Result<(), Error> {} or async::<Result<(), Error> {}, but those are uuuugly.

    CC #62570, as it is not the same error, but it is similar enough code that these two errors will likely happen in short temporal distance of each other.

  8. cramertj commented on Aug 28, 2019

    @cramertj
    Member

    @estebank did you mean to include the ? after the x in your example above?

  9. 2 remaining items

  10. estebank commented on Aug 29, 2019

    @estebank
    Contributor

    You're absolutely right. Need more coffee.

  11. programmerjake commented on Aug 29, 2019

    @programmerjake
    Member

    doesn't ? still use From rather than Into, or did I miss some happy RFC?

  12. added
    D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.
    on Oct 5, 2019
  13. removed
    requires-nightlyThis issue requires a nightly compiler in some way. When possible, use a F-* label instead.
    on Nov 12, 2019
  14. added 3 commits that reference this issue on Dec 11, 2019
  15. Dylan-DPC commented on Mar 24, 2023

    @Dylan-DPC
    Member

    Current output:

    error[[E0282]](https://doc.rust-lang.org/nightly/error_codes/E0282.html): type annotations needed
      --> src/main.rs:11:9
       |
    11 |         Ok(())
       |         ^^ cannot infer type of the type parameter `E` declared on the enum `Result`
       |
    help: consider specifying the generic arguments
       |
    11 |         Ok::<(), E>(())
       |           +++++++++
    
  16. estebank commented on Mar 25, 2023

    @estebank
    Contributor

    The only thing left is for inference to detect that E could have been Error and suggest that.

  17. added
    D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.
    on Aug 4, 2023
  18. added
    D-papercutDiagnostics: An error or lint that needs small tweaks.
    and removed
    C-bugCategory: This is a bug.
    D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.
    on Oct 18, 2023
  19. KalyanKadiyala commented on May 6, 2025

    @KalyanKadiyala

    Not a question, but a comment with something that I tried to resolve annoyance at call-site. The ?-operator is used to extract value from a Result. Wanted to check, if there's been any progress on the topic (less async itself). The coherence rules prevent adding implicit coercion support for concrete types in my case. This can be the case with any other remotely defined Traits.

    Briefly,

    • When I explicitly provide type annotations, the call-site assignment is inferred to expected error type on the Result return value.
    Image
    • However, if I leave it to inference, the valid inferred result loses type specificity on the error variant, as shown below:
    Image

    Though a deviation from the standard approach of using the ? operator, I've added an implementation support that wraps ? operator usage with expected concrete types on the Result type using a separate extract method. Here's the impl:

    Image

    And here's the call-site, where the assigned value from the closure gets resolved (by inference) to expected Result's error value type:

    Image

    Like to share this and seek any comments/suggestions. I'm using Rust 1.86 stable build.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-async-awaitArea: Async & AwaitA-diagnosticsArea: Messages for errors, warnings, and lintsA-inferenceArea: Type inferenceA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`AsyncAwait-TriagedAsync-await issues that have been triaged during a working group meeting.D-papercutDiagnostics: An error or lint that needs small tweaks.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions