rust-lang / rust-lang/rust

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

Open
#119,765 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the Rust example with the reported nightly compiler and inspect the diagnostic code responsible for the ? conversion error. Add coverage for the ok_or closure case and equivalent methods, with completion marked by a diagnostic that suggests ok_or_else without regressing other conversion errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.