Skip to content

False positive in unnecessary_to_owned when a mutable borrow would cause a compiler error #14918

Open
@shssoichiro

Description

@shssoichiro

Summary

Minimal reproduction:

pub fn one_borrow(data: &mut [u8]) {
    multiple_borrows(
        // warning: unnecessary use of `to_vec`
        // but if we remove `to_vec()`, we get
        // error[E0502]: cannot borrow `*data` as mutable because it is also borrowed as immutable
        &data[0..8].to_vec(),
        &mut data[8..16]
    );
}

fn multiple_borrows(src:&[u8], dest: &mut [u8]){
    // Doesn't really matter what's in this function
    if src.len() == dest.len() {
        dest.copy_from_slice(src);
    }
}

(I know in this contrived use case you can use split_at_mut, but this can occur in cases where that isn't possible)

Lint Name

unnecessary_to_owned

Reproducer

I tried this code:

pub fn one_borrow(data: &mut [u8]) {
    multiple_borrows(
        // warning: unnecessary use of `to_vec`
        // but if we remove `to_vec()`, we get
        // error[E0502]: cannot borrow `*data` as mutable because it is also borrowed as immutable
        &data[0..8].to_vec(),
        &mut data[8..16]
    );
}

fn multiple_borrows(src:&[u8], dest: &mut [u8]){
    // Doesn't really matter what's in this function
    if src.len() == dest.len() {
        dest.copy_from_slice(src);
    }
}

I saw this happen:

warning: unnecessary use of `to_vec`

I expected to see this happen:

No warning.

Version

occurs on both rustc 1.87.0 (17067e9ac 2025-05-09) and rustc 1.89.0-nightly (283db70ac 2025-05-25)

rustc 1.89.0-nightly (283db70ac 2025-05-25)
binary: rustc
commit-hash: 283db70ace62a0ae704a624e43b68c2ee44b87a6
commit-date: 2025-05-25
host: x86_64-unknown-linux-gnu
release: 1.89.0-nightly
LLVM version: 20.1.5

Additional Labels

@rustbot label +I-suggestion-causes-error

Metadata

Metadata

Assignees

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