rust-lang / rust-lang/rust-clippy

[regression in 1.70] [clippy] redundant clone ; cloned value is neither consumed nor mutated

Open
#10,870 3 comments 5 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

Code
#[derive(Clone)]
pub struct Foo(&'static str);

pub fn foo(a: Foo, b: Option<Foo>) -> String {
    let b = if let Some(b) = b { b } else { a.clone() };
    let mut result = String::new();
    result.push_str(a.0);
    result.push_str(b.0);
    result
}
Current output
warning: redundant clone
 --> src/lib.rs:5:46
  |
5 |     let b = if let Some(b) = b { b } else { a.clone() };
  |                                              ^^^^^^^^ help: remove this
  |
note: cloned value is neither consumed nor mutated
 --> src/lib.rs:5:45
  |
5 |     let b = if let Some(b) = b { b } else { a.clone() };
  |                                             ^^^^^^^^^
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone
  = note: `#[warn(clippy::redundant_clone)]` on by default
Desired output
Nothing
Rationale and extra context

This is what the compiler says without the clone:

error[[E0382]](https://doc.rust-lang.org/stable/error_codes/E0382.html): borrow of moved value: `a`
 --> src/lib.rs:7:21
  |
4 | pub fn foo(a: Foo, b: Option<Foo>) -> String {
  |            - move occurs because `a` has type `Foo`, which does not implement the `Copy` trait
5 |     let b = if let Some(b) = b { b } else { a };
  |                                             - value moved here
6 |     let mut result = String::new();
7 |     result.push_str(a.0);
  |                     ^^^ value borrowed here after move
  |
help: consider cloning the value if the performance cost is acceptable
  |
5 |     let b = if let Some(b) = b { b } else { a.clone() };
  |                                              ++++++++
Other cases

No response

Anything else?

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 reduced Rust example in src/lib.rs and start by tracing the redundant_clone lint behavior that produces the warning. Compare the lint result with the compiler error shown in the issue; done means this valid example no longer emits the redundant-clone warning.

Written by the indexing model from the issue text.

Assessment

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