rust-lang / rust-lang/rust-clippy
False positive in clippy::useless_asref
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
I recently updated to Rust 1.69.0, and clippy gave me a few new warnings on my project. Cool, nothing unusual there.
However, once I applied one of the suggestions, I realized my tests had broken horribly.
Turns out, clippy had suggested a call to as_ref() was useless when in fact it was helping with some sort of type conversion magic. I was using as_ref() to help me get a mutable view into an immutable slice.
In the end, I ended up using a Cursor to get my mutable view into an immutable slice, but I thought it helpful to report that clippy's suggestion broke my build, and the compiler's suggestion did not allow me to keep my mutable view into an immutable slice.
Lint Name
useless_asref
Reproducer
Minimal reproduction:
use std::io::Read;
pub fn read_byte<R: Read>(r: &mut R) {
let mut buf = [0u8; 1];
r.read_exact(&mut buf).unwrap();
println!("First byte: {}", buf[0]);
}
pub fn main() {
let data: &[u8] = &[3; 10];
read_byte(&mut data.as_ref());
}
cargo clippy outputs this:
--> src/main.rs:11:20
|
11 | read_byte(&mut data.as_ref());
| ^^^^^^^^^^^^^ help: try this: `data`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#useless_asref
= note: `#[warn(clippy::useless_asref)]` on by default
However, removing the as_ref() causes a compile-time error, saying that it cannot borrow data as &mut, which makes sense.
Version
rustc 1.69.0 (84c898d65 2023-04-16)
binary: rustc
commit-hash: 84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc
commit-date: 2023-04-16
host: x86_64-unknown-linux-gnu
release: 1.69.0
LLVM version: 15.0.7
Additional Labels
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the provided minimal reproduction with Rust 1.69.0 and inspect the useless_asref lint implementation and its existing regression tests. Confirm the lint's suggestion incorrectly removes a needed conversion, then add coverage showing the mutable view remains valid and the suggestion is no longer emitted.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100