rust-lang / rust-lang/rust-clippy
needsless_borrow is sometimes too aggressive
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Description
needsless_borrow warns on some code that I consider idiomatic, but is nice to have for other code so it'd be a shame to allow it.
Specifically I am talking about code like this:
use std::path::PathBuf;
use std::fs;
fn main() {
let file = PathBuf::new();
fs::read_to_string(&file).unwrap();
}
Clippy asks me to remove the &. However, there is no benefit from doing that: read_to_string takes an AsRef, so effectively a reference, and it will still clone the buffer.
The disadvantage of following clippy's advice is that when later, the function is extended and file is used again, there would be an error:
use std::path::PathBuf;
use std::fs;
fn main() {
let file = PathBuf::new();
fs::read_to_string(file).unwrap();
fs::write(file, "content").unwrap(); // error, `file` was moved
}
For this reason I think it is generally better to use &file for AsRef arguments: there is no performance cost, and it properly reflects that the function does not actually want or need ownership of this data -- and keeps the code working for future changes.
Clippy's recommendation poses the risk that someone could end up with code like this
use std::path::PathBuf;
use std::fs;
fn main() {
let file = PathBuf::new();
fs::read_to_string(file.clone()).unwrap();
fs::write(file, "content").unwrap();
}
Which is silly because there is a needless copy.
I think needsless_borrows should not consider & needless when the argument type is impl AsRef.
Version
rustc 1.66.0-nightly (9565dfeb4 2022-10-28)
binary: rustc
commit-hash: 9565dfeb4e6225177bbe78f18cd48a7982f34401
commit-date: 2022-10-28
host: x86_64-unknown-linux-gnu
release: 1.66.0-nightly
LLVM version: 15.0.2
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 locating the needsless_borrow lint in the rust-clippy repository and reproduce the issue with the provided PathBuf and std::fs examples. Determine how arguments using AsRef are classified. Done when the idiomatic borrow is no longer warned about while genuinely needless borrows remain covered by the lint's existing behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100