Skip to content

Confusing compiler error when returning a Result<Result> via ?-operator #86547

Open
@sdroege

Description

@sdroege

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9aac41ba36103dac1f4ae20fa30c86f0

fn foo(x: Option<i32>) -> Result<(), &'static str> {
    let _ = x.ok_or_else(|| Err("nope"))?;
    Ok(())
}

fn main() {
    println!("{:?}", foo(Some(1)));
}

The current output is:

error[E0277]: `?` couldn't convert the error to `&str`
 --> src/main.rs:2:41
  |
1 | fn foo(x: Option<i32>) -> Result<(), &'static str> {
  |                           ------------------------ expected `&str` because of this
2 |     let _ = x.ok_or_else(|| Err("nope"))?;
  |                                         ^ the trait `From<Result<_, &str>>` is not implemented for `&str`
  |
  = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
  = note: required by `from`

Ideally the output would mention the double-Result wrapping ("got type Result<Result<...>> expected ...") and suggest removing one layer or Result::flatten() or similar.

It kind of does the former already if you squint but it's far from obvious ("the trait From<Result<_, &str>> is not implemented for &str").

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