rust-lang / rust-lang/rust-clippy

New lint: early return variables

Open
#8,377 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

What it does

detect variables that are defined/initialized but not used before an early return

Lint Name

early-variable

Category

perf

Advantage
  • Safes computation time
  • Maybe safes variable initialization?
Drawbacks

Users might like to keep the position of their variable declaration

Example
fn main() {
    let x = 5;

    if let Some(arg) = env::args().nth(1) {
        match arg.as_str() {
            "-h" | "--help" => {
                return;
            }
            _ => {}
        }
    }

    dbg!(&x);
}

Could be written as:

fn main() {
    if let Some(arg) = env::args().nth(1) {
        match arg.as_str() {
            "-h" | "--help" => {
                return;
            }
            _ => {}
        }
    }

    let x = 5;

    dbg!(&x);
}

Real world example https://github.com/extrawurst/gitui/pull/660#discussion_r619650270


I tried implementing it, but I have no idea how to detect such a case and a foreign code base does not make it easier

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.

Research direction

Start with the Rust examples and the linked gitui discussion to clarify the intended lint behavior and its edge cases. Then read Clippy's existing lint implementations and tests to determine how an early return and variable-use analysis should be represented. Done means the lint reliably identifies the shown pattern, avoids false positives, and has coverage for the agreed cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.