rust-lang / rust-lang/rust-clippy

Clippy warns about or_insert_with usage in implementation of or_default

Open
#11,341 1 comment 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

The imbl crate (https://github.com/jneem/imbl/tree/8756e765d8f76688da333b751db14287ae862c20) defines two Entry types at src/ord/map.rs and src/hash/map.rs with these methods:

/// Insert a default value if there was no value already, and
/// return a mutable reference to the value.
pub fn or_default(self) -> &'a mut V
where
    V: Default,
{
    self.or_insert_with(Default::default)
}

/// Get the key for this entry.
#[must_use]
pub fn key(&self) -> &K {
    match self {
        Entry::Occupied(entry) => entry.key(),
        Entry::Vacant(entry) => entry.key(),
    }
}

and clippy warns:

warning: use of `or_insert_with` to construct default value
    --> src/hash/map.rs:1419:14
     |
1419 |         self.or_insert_with(Default::default)
     |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `or_default()`
     |
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_or_default

Applying this suggestions makes or_default recurse unconditionally (which clippy then also warns about, luckily).

Lint Name

unwrap_or_default

Reproducer

No response

Version
rustc 1.73.0-nightly (180dffba1 2023-08-14)
binary: rustc
commit-hash: 180dffba142c47240ca0d93096ce90b9fd97c8d7
commit-date: 2023-08-14
host: x86_64-unknown-linux-gnu
release: 1.73.0-nightly
LLVM version: 17.0.0
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

Reproduce the warning with the imbl implementations in src/ord/map.rs and src/hash/map.rs using the reported unwrap_or_default lint and Rust version. Check why the suggested or_default replacement recurses, then verify that the lint no longer produces an invalid suggestion or warning for these methods without regressing the intended lint behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 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.