Skip to content

Bad/confusing error message with Residuals #90863

Closed
@simbleau

Description

@simbleau

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1b1c18cee65bf066a53f2c1a8c3653d0

extern crate anyhow; // 1.0.45
use anyhow::Result;

fn give_result() -> Result<()> {
    Ok(())
}

pub fn main() {
    give_result()?; // <--- Notice the `?`
}

The current output is:

   Compiling playground v0.0.1 (/playground)
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
   --> src/main.rs:9:18
    |
8   | / pub fn main() {
9   | |     give_result()?;
    | |                  ^ cannot use the `?` operator in a function that returns `()`
10  | | }
    | |_- this function should return `Result` or `Option` to accept `?`
    |
    = help: the trait `FromResidual<Result<Infallible, anyhow::Error>>` is not implemented for `()`
note: required by `from_residual`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` due to previous error

What is wrong?:

  • The indication on which offending function that does not return Result or Option could be better. It could be more explicit on whether main() or get_result() needs to return Result or Option.
  • The helper text help: the trait `FromResidual<Result<Infallible, anyhow::Error>>` is not implemented for `()` note: required by `from_residual`. is help text for the internal compiler which does not need to be passed to developers. It's generally incomprehensible to most who do not know that this trait bound error has nothing to do with their code and would confuse a mass of new Rust programmers.

Ideally the output should look like:

   Compiling playground v0.0.1 (/playground)
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
   --> src/main.rs:9:18
    |
8   | / pub fn main() {
    | |            ^^ `main` does not return `Result` or `Option` to accept `?`
9   | |     give_result()?;
    | |                  ^ cannot use the `?` operator in a function that returns `()`
10  | | }
    | |_- this function should return `Result` or `Option` to accept `?`
    |

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` due to previous error

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-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