rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

assigning_clones: suggestion causes error because of borrowed target

Open samueltardieu opened this issue 2 months ago • 1 comments

Summary

When the entity being cloned borrows the former content of the target, the target cannot be replaced using .clone_into().

Reproducer

I tried this code:

use std::path::PathBuf;

#[allow(unused)]
fn main() {
    let mut path = PathBuf::from("/a/b/c");
    path = path.components().as_path().to_owned();
}

I expected to see this happen: no suggestion

Instead, this happened:

warning: assigning the result of `ToOwned::to_owned()` may be inefficient
 --> src/main.rs:6:5
  |
6 |     path = path.components().as_path().to_owned();
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `clone_into()`: `path.components().as_path().clone_into(&mut path)`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#assigning_clones
  = note: `#[warn(clippy::assigning_clones)]` on by default

Applying the suggestion then leads to:

error[E0502]: cannot borrow `path` as mutable because it is also borrowed as immutable
 --> src/main.rs:6:44
  |
6 |     path.components().as_path().clone_into(&mut path);
  |     ----                        ---------- ^^^^^^^^^ mutable borrow occurs here
  |     |                           |
  |     |                           immutable borrow later used by call
  |     immutable borrow occurs here

Version

rustc 1.78.0 (9b00956e5 2024-04-29)
binary: rustc
commit-hash: 9b00956e56009bab2aa15d7bff10916599e3d6d6
commit-date: 2024-04-29
host: x86_64-unknown-linux-gnu
release: 1.78.0
LLVM version: 18.1.2

Additional Labels

@rustbot label I-suggestion-causes-error

samueltardieu avatar May 02 '24 15:05 samueltardieu

Found in https://github.com/uutils/coreutils/pull/6330

samueltardieu avatar May 02 '24 15:05 samueltardieu