Skip to content

Add clearer error message when mistakenly using ok_or instead of ok_or_else and equivalent method #119765

Open
@StealthyKamereon

Description

@StealthyKamereon

Code

fn main() -> Result<(), bool> {
    None.ok_or(|| true)?
}

Current output

error[E0277]: `?` couldn't convert the error to `bool`
 --> src/main.rs:3:24
  |
2 | fn main() -> Result<(), bool> {
  |              ---------------- expected `bool` because of this
3 |     None.ok_or(|| true)?
  |                        ^ the trait `From<{closure@src/main.rs:3:16: 3:18}>` is not implemented for `bool`
  |
  = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
  = help: the following other types implement trait `FromResidual<R>`:
            <Result<T, F> as FromResidual<Yeet<E>>>
            <Result<T, F> as FromResidual<Result<Infallible, E>>>
  = note: required for `Result<(), bool>` to implement `FromResidual<Result<Infallible, {closure@src/main.rs:3:16: 3:18}>>`

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

Desired output

`?` expected `bool` for `Err` variant but found `{closure@src/main.rs:3:16: 3:18}`.
Did you meant to use `ok_or_else` ?

Rationale and extra context

We could use the fact that the found type is a closure to detect the user probably wanted to use the *_else variant of the method.

Other cases

No response

Rust Version

rustc 1.77.0-nightly (ca663b06c 2024-01-08)
binary: rustc
commit-hash: ca663b06c5492ac2dde5e53cd11579fa8e4d68bd
commit-date: 2024-01-08
host: x86_64-pc-windows-msvc
release: 1.77.0-nightly
LLVM version: 17.0.6

Anything else?

No response

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