rust-lang / rust-lang/rust-clippy

Unnecessary cast for non-literal expressions

Open
#8,237 2 comments 1 reaction 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

There's an unnecessary_cast lint for literals. Unnecessary casting can also happen for expressions. For example, I've refactored a codebase to remove uses of c_int, which left me with lots of as _ conversions that were no longer doing anything.

I'm proposing this as a new lint, not an extension to the unnecessary_cast, because users may want to enable/disable this lint separately.

Lint Name

unnecessary_cast_expression

Category

complexity

Advantage

Clarifies intent of the code. Removes doubt whether the cast is intentional, or written because of confusion about expression's type.

Drawbacks

as _ is easier to read and write than try_into().unwrap(), and code that works with non-generic types that are changed by conditional compilation may prefer the terser syntax.

#[cfg(foo)]
type Int = u32;

#[cfg(not(foo))]
type Int = usize;

fn main() { takes_usize(my_int as _); }
Example
fn takes_usize(_x: usize) {}

fn main() {
    takes_usize([1,2,3].len() as _);
}

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 by examining the existing unnecessary_cast lint and how Clippy defines lints in the complexity category. Determine how to identify casts on expressions that have no effect, while preserving the separate unnecessary_cast_expression name and the conditional-compilation example; done means the proposed cases are detected without collapsing the two lints.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.