Skip to content

clippy::useless_asref warns in cases where map callback performs a method call before a clone #12135

@alex

Description

@alex

Summary

The new clippy::useless_asref warning is overly aggressive.

Lint Name

clippy::useless_asref

Reproducer

Given the following code:

pub struct Struct {
    field: Option<InnerStruct>
}

#[derive(Clone)]
pub struct Foo;

struct InnerStruct {
    x: Foo,
}

impl InnerStruct {
    fn method(&self) -> &Foo {
        &self.x
    }
}

pub fn f(x: &Struct) -> Option<Foo> {
    x.field.as_ref().map(|v| v.method().clone())
}

Clippy emits the following warning:

warning: this call to `as_ref.map(...)` does nothing
  --> src/lib.rs:19:5
   |
19 |     x.field.as_ref().map(|v| v.method().clone())
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `x.field.clone()`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#useless_asref
   = note: `#[warn(clippy::useless_asref)]` on by default

warning: `x` (lib) generated 1 warning (run `cargo clippy --fix --lib -p x` to apply 1 suggestion)
    Finished dev [unoptimized + debuginfo] target(s) in 0.16s

However, this is not correct, x.field.clone() totally drops the call to method().

Version

rustc 1.77.0-nightly (62d7ed4a6 2024-01-11)
binary: rustc
commit-hash: 62d7ed4a6775c4490e493093ca98ef7c215b835b
commit-date: 2024-01-11
host: aarch64-apple-darwin
release: 1.77.0-nightly
LLVM version: 17.0.6

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