Skip to content

cloned_ref_to_slice_refs suggestion may cause error #14856

@pv42

Description

@pv42

Summary

cloned_ref_to_slice_refs lint may trigger when the clone() prevents borrow checker issues.

Lint Name

cloned_ref_to_slice_refs

Reproducer

I tried this code:

use std::sync::RwLock;

#[derive(Clone)]
struct Foo;
struct Bar;

struct FooBar {
    foo: Foo,
    bar: Bar,
}

fn main() {
    let lock = RwLock::new(FooBar{
        foo: Foo,
        bar: Bar,
    });
    let mut foobar = lock.write().unwrap();
    let f = &foobar.foo;

    do_something(&[f.clone()], &mut foobar.bar);
    //do_something(std::slice::from_ref(f), &mut foobar_ref.bar);
}

fn do_something(_foos: &[Foo], _bar: &mut Bar) {
    // ...
}

I saw this happen:

warning: this call to `clone` can be replaced with `std::slice::from_ref`
  --> src\foobar.rs:20:18
   |
20 |     do_something(&[f.clone()], &mut foobar.bar);
   |                  ^^^^^^^^^^^^ help: try: `std::slice::from_ref(f)`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cloned_ref_to_slice_refs

I expected to see this happen:
Nothing.
Following the suggestion leads to the following error:

error[E0502]: cannot borrow `foobar` as mutable because it is also borrowed as immutable
  --> src\foobar.rs:21:48
   |
18 |     let f= &foobar.foo;
   |             ------ immutable borrow occurs here
...
21 |     do_something(std::slice::from_ref(f), &mut foobar.bar);
   |     ------------                               ^^^^^^ mutable borrow occurs here
   |     |
   |     immutable borrow later used by call

Version

rustc 1.89.0-nightly (60dabef95 2025-05-19)
binary: rustc
commit-hash: 60dabef95a3de3ec974dcb50926e4bfe743f078f
commit-date: 2025-05-19
host: x86_64-pc-windows-msvc
release: 1.89.0-nightly
LLVM version: 20.1.5

Additional Labels

@rustbot label +I-suggestion-causes-error

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 haveI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions