Skip to content

Lint unwrap_or_default does not check whether suggested or_default function actually exists #11390

@thomaseizinger

Description

@thomaseizinger

Summary

Some data structures might have an or_insert_with function but not a corresponding or_default function. In those cases, the lint should not fire.

Lint Name

unwrap_or_default

Reproducer

https://play.rust-lang.org/?version=beta&mode=debug&edition=2021&gist=13480064b9cee4e0be677a77cc118370

I tried this code:

pub(crate) enum Entry<K, V> {
    A(K),
    B(V),
}

impl<K, V> Entry<K, V> {
    pub(crate) fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'static mut V {
        todo!()
    }
}

fn foo(entry: Entry<String, String>) {
    let _ = entry.or_insert_with(String::default);
}

fn main() {

}

I saw this happen:

warning: use of `or_insert_with` to construct default value
  --> src/main.rs:13:19
   |
13 |     let _ = entry.or_insert_with(String::default);
   |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `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 this happen:

No lint warning because there is no or_default function.

Version

rustc 1.73.0-beta.1 (680cdf816 2023-08-21)
binary: rustc
commit-hash: 680cdf8168a906b4ea80af673c64e4a16f77be57
commit-date: 2023-08-21
host: x86_64-unknown-linux-gnu
release: 1.73.0-beta.1
LLVM version: 17.0.0

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions