rust-lang / rust-lang/rust-clippy

unnecessary_lazy_evaluations could give more targeted suggestion when unwrapping

Open
#15,465 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-enhancement S-triage
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

Given this code which ensures definitely contains a value:

let maybe: Option<u32> = None;
let definitely = maybe.or_else(|| Some(7)).unwrap();
println!("{definitely}");

Better code would be:

let definitely = maybe.unwrap_or(7);

Right now clippy suggests maybe.or(Some(7)).unwrap():

warning: unnecessary closure used to substitute value for `Option::None`
 --> src/main.rs:3:22
  |
3 |     let definitely = maybe.or_else(|| Some(7)).unwrap();
  |                      ^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_lazy_evaluations
  = note: `#[warn(clippy::unnecessary_lazy_evaluations)]` on by default
help: use `or` instead
  |
3 -     let definitely = maybe.or_else(|| Some(7)).unwrap();
3 +     let definitely = maybe.or(Some(7)).unwrap();
  |

It'd be great to notice the unwrap and have the suggestion be unwrap_or (or unwrap_or_else) rather than or(_).unwrap()

Reproducer

I tried this code:

fn main() {
    let maybe: Option<u32> = None;
    let definitely = maybe.or_else(|| Some(7)).unwrap();
    println!("{definitely}");
}

I expected to see this happen: Suggestion to use unwrap_or

Instead, this happened: Suggestion to use or and then unwrap

Version
rustc 1.88.0 (6b00bc388 2025-06-23)
binary: rustc
commit-hash: 6b00bc3880198600130e1cf62b8f8a93494488cc
commit-date: 2025-06-23
host: aarch64-apple-darwin
release: 1.88.0
LLVM version: 20.1.5
Additional Labels

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 locating the unnecessary_lazy_evaluations lint and reproduce the provided Option example. Update the suggestion so the unwrap case recommends unwrap_or, or unwrap_or_else when appropriate, then verify the diagnostic no longer recommends chaining or and unwrap.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.