Skip to content

manual_unwrap_or_default fails to consider deref type coercion #12666

Closed
@MingweiSamuel

Description

@MingweiSamuel

Summary

clippy::manual_unwrap_or_default fails to consider deref type coercion for the returned values

Lint Name

manual_unwrap_or_default

Reproducer

Playground: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=b8497c471fa7991f62cb1ef29fe18e31

fn foo(s: &Option<String>) -> &str {
    if let Some(s) = s {
        s
    } else {
        ""
    }
}

fn bar(s: Option<&String>) -> &str {
    if let Some(s) = s {
        s
    } else {
        ""
    }
}

Clippy suggests the code s.unwrap_or_default() and then rust suggests &s.unwrap_or_default(), which naturally will not work due to returning a reference to a temporary local value.

A way to simplify foo would be to use as_deref() first:

s.as_deref().unwrap_or_default()

A way to simplify bar would be to deref the inner value using map first:

s.map(std::ops::Deref::deref).unwrap_or_default()
// or
s.map(|s| &**s).unwrap_or_default()

Version

Playground:
Nightly channel
Build using the Nightly version: 1.79.0-nightly
(2024-04-08 ab5bda1aa70f707014e2)

Local:
rustc 1.79.0-nightly (8b2459c1f 2024-04-09)
binary: rustc
commit-hash: 8b2459c1f21187f9792d99310171a15e64feb9cf
commit-date: 2024-04-09
host: x86_64-apple-darwin
release: 1.79.0-nightly
LLVM version: 18.1.3

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 haveL-suspiciousLint: Belongs in the suspicious lint group

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions