Skip to content

Suggest unwrap_or_else when a closure is passed to unwrap_or instead of suggesting calling it #102320

Closed
@amrbashir

Description

@amrbashir

rustc should suggest unwrap_or_else if the argument is a closure instead of suggesting to call the closure

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

fn main() {
  let x = "com.example.app";
  let y: Option<&str> = None;
  let s = y.unwrap_or(|| x.split('.').nth(1).unwrap());
}

The current output is:

error[[E0308]](https://doc.rust-lang.org/stable/error-index.html#E0308): mismatched types
 --> src/main.rs:4:23
  |
4 |   let s = y.unwrap_or(|| x.split('.').nth(1).unwrap());
  |             --------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `&str`, found closure
  |             |
  |             arguments to this function are incorrect
  |
  = note: expected reference `&str`
               found closure `[closure@src/main.rs:4:23: 4:25]`
note: associated function defined here
help: use parentheses to call this closure
  |
4 |   let s = y.unwrap_or((|| x.split('.').nth(1).unwrap())());
  |                       +                               +++

Ideally the output should look like:

error[[E0308]](https://doc.rust-lang.org/stable/error-index.html#E0308): mismatched types
 --> src/main.rs:4:23
  |
4 |   let s = y.unwrap_or(|| x.split('.').nth(1).unwrap());
  |             --------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `&str`, found closure
  |             |
  |             arguments to this function are incorrect
  |
  = note: expected reference `&str`
               found closure `[closure@src/main.rs:4:23: 4:25]`
note: associated function defined here
help: use "unwrap_or_else"
  |
4 |   let s = y.unwrap_or_else(|| x.split('.').nth(1).unwrap());
  |                      +++++                              

Metadata

Metadata

Assignees

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