Rust should warn for unused "pure" objects
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
Code
use std::path::PathBuf;
fn main() {
let mut buf = PathBuf::new();
buf.push("/something");
}
Current output
Compiling playground v0.0.1 (/playground)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.64s
Running `target/debug/playground`
Desired output
Warning: buf is written to but never read.
Rationale and extra context
Here push is a side effect free operation, it only modifies memory belonging to the object. With some sort of attribute or other annotation it should be possible to tell rustc about this, allowing more warnings about unused objects to be produced. The standard library should use such attributes where appropriate (various methods on String, str, PathBuf, etc).
Do note that for generic types such as Vec<T> this might be tricky, as T would also have to be side effect free (e.g. warning about Vec<i32>::push is good, Vec<MutexGuard>::push is probably not), I'm not sure about the best way to handle that, or if it should just be punted to the future.
Other cases
No response
Rust Version
❯ rustc --version --verbose
rustc 1.79.0 (129f3b996 2024-06-10)
binary: rustc
commit-hash: 129f3b9964af4d4a709d1383930ade12dfe7c081
commit-date: 2024-06-10
host: x86_64-unknown-linux-gnu
release: 1.79.0
LLVM version: 18.1.7
Anything else?
Having a warning for this would have saved me time in the profiler (yes, in a hot loop left over (otherwise refactored) pathbuf construction was actually causing a noticable slowdown in my program).
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 reproducing the sample with rustc 1.79.0 and inspect how unused values and method calls are currently linted. Review the standard-library methods mentioned, including PathBuf, String, and str, along with the generic Vec concern. Done means the proposed behavior and scope are defined well enough to warn for the demonstrated case without incorrectly warning about side effects.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 28/100