rust-lang / rust-lang/rust-clippy

`unwrap_or_default` suggests replacing `T::new`

Open
#11,631 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

unwrap_or_default suggests replacing unwrap_or_else(T::new) with unwrap_or_default() when Default is implemented via new.

Lint Name

unwrap_or_default

Reproducer

I tried this code (playground):

pub struct Foo(u32);

impl Foo {
    fn new() -> Self {
        Self(0)
    }
}

impl Default for Foo {
    fn default() -> Self {
        Self::new()
    }
}

pub fn foo(x: Option<Foo>) -> Foo {
    x.unwrap_or_else(Foo::new)
}

I saw this happen:

warning: use of `unwrap_or_else` to construct default value
  --> src/lib.rs:16:7
   |
16 |     x.unwrap_or_else(Foo::new)
   |       ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_default()`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_or_default
   = note: `#[warn(clippy::unwrap_or_default)]` on by default

I expected to see no warning. The implementation of Default could be changed to something other than new, potentially making all code that was changed to unwrap_or_default invalid.

Version
rustc 1.73.0 (cc66ad468 2023-10-03)
binary: rustc
commit-hash: cc66ad468955717ab92600c770da8c1601a4ff33
commit-date: 2023-10-03
host: aarch64-apple-darwin
release: 1.73.0
LLVM version: 17.0.2
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 with the unwrap_or_default lint implementation and the reproducer in the issue. Check how the lint decides that Foo::new constructs a default value, then verify the behavior against the shown Rust example. Done means the lint no longer suggests unwrap_or_default() for this case while preserving its valid suggestions.

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
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.