Skip to content

Improved messaging for ? within a function with () return type - E0277 #101281

Closed
@amanjeev

Description

@amanjeev

This is mostly a suggestion if there can be some improvement to the diagnostics.

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

use std::num::ParseIntError;

fn retoptionres(x: &str) -> Result<Option<u32>, ParseIntError> {
    let n = x.parse::<u32>()?;
    Ok(Some(n))
}

fn main() {
    let x = retoptionres("4")??;
    println!("{:?}", x);
}

The current output is:

Compiling playground v0.0.1 (/playground)
error[[E0277]](https://doc.rust-lang.org/stable/error-index.html#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:30
   |
8  | / fn main() {
9  | |     let x = retoptionres("4")??;
   | |                              ^ cannot use the `?` operator in a function that returns `()`
10 | |     println!("{:?}", x);
11 | | }
   | |_- this function should return `Result` or `Option` to accept `?`
   |
   = help: the trait `FromResidual<Result<Infallible, ParseIntError>>` is not implemented for `()`

Ideally the output should look like:

Compiling playground v0.0.1 (/playground)
error[[E0277]](https://doc.rust-lang.org/stable/error-index.html#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:30
   |
8  | / fn main() {
9  | |     let x = retoptionres("4")??;
   | |                              ^ cannot use the `?` operator in a function that returns `()`
10 | |     println!("{:?}", x);
11 | | }
   | |_- this function (crate::main) should return `Result` or `Option` to accept `?`
   |    - Hint: add an `Option` or `Result` return type to `main`
   = help: the trait `FromResidual<Result<Infallible, ParseIntError>>` is not implemented for `()`

This error is easier to miss because busy-ness and not knowing which function needs the return type.

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