Skip to content

implicit_clone shouldn't lint when called on a reference #11281

@scottmcm

Description

@scottmcm

Summary

I agree that for something like https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=bba81815705c82d64c18911576b5244a

#[deny(clippy::implicit_clone)]
pub fn dup(x: String) -> (String, String) {
    (x.to_owned(), x)
}

This is a good lint, because x is already owned, so clone better describes what's happening.

However, today the lint also complains if I'm starting with a &String, which definitely isn't owned, and I'd very much like to use .to_owned() on such things to clarify that what I want is something owned (as I describe in further detail in https://users.rust-lang.org/t/current-guidance-on-str-to-string-to-owned-vs-to-string/75754/7?u=scottmcm or https://users.rust-lang.org/t/what-is-the-difference-between-clone-and-to-owned/54705/3?u=scottmcm).

As such, I think this lint is over-aggressive and should be slightly tuned back. I would say that if the call to to_owned ends up needing auto-ref, like it does in the dup example above, it should lint, but if it doesn't need autoref (because the LHS is already a reference) then it should stop linting.

(Opened this issue because it came up on discord.)

Lint Name

implicit_clone

Reproducer

I tried this code:

#[deny(clippy::implicit_clone)]
pub fn foo(x: &String) -> String {
    x.to_owned()
}

I saw this happen:

error: implicitly cloning a `String` by calling `to_owned` on its dereferenced type
 --> src/lib.rs:3:5
  |
3 |     x.to_owned()
  |     ^^^^^^^^^^^^ help: consider using: `x.clone()`
  |

I expected to see this happen:

It compiles fine.

Version

(2023-07-31 db7ff98a72f3e742b641)

Additional Labels

No response

Metadata

Metadata

Assignees

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