rust-lang / rust-lang/rust-clippy

Suggest to remove unneeded `.as_slice()` and similar

Open
#16,929 1 comment 0 reactions 1 assignee View on GitHub

@Kokoro2336 is already working on this.

Since May 1, 2026.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

This lint would detect redundant Vec::as_slice() and similar calls when the resulting slice is only used to call a method that would also resolve directly on the Vec through deref coercion.

Advantage
  • Cleaner, shorter, easier to read code
Drawbacks

No response

Example

All usages of .as_slice() and .as_mut_slice() can be removed. Note that as_mut_slice() is a extended case because it does not actually need mut either.

#![warn(clippy::pedantic)]

trait SliceExt {
    fn my_len(&self) -> usize;
}
impl SliceExt for [u32] {
    fn my_len(&self) -> usize {
        self.len()
    }
}
fn as_ref(vals: &mut Vec<u32>) {
    assert_eq!(vals.as_slice().len(), vals.len()); //~ as_slice() not needed
    assert_eq!(vals.as_mut_slice().len(), vals.len()); //~ as_mut_slice() not needed
}
fn as_owned_ex(mut vals: Vec<u32>) {
    assert_eq!(vals.as_slice().my_len(), vals.my_len()); //~ as_slice() not needed
    assert_eq!(vals.as_mut_slice().my_len(), vals.my_len()); //~ as_mut_slice() not needed
}
fn as_ref_ex(vals: &mut Vec<u32>) {
    assert_eq!(vals.as_slice().my_len(), vals.my_len()); //~ as_slice() not needed
    assert_eq!(vals.as_mut_slice().my_len(), vals.my_len()); //~ as_mut_slice() not needed
}
fn main() {
    as_ref(&mut vec![1_u32, 2, 3]);
    as_owned_ex(vec![1_u32, 2, 3]);
    as_ref_ex(&mut vec![1_u32, 2, 3]);
}
Comparison with existing lints

No response

Additional Context

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.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.