Skip to content

needless_type_cast suggests defining bindings as their cast type #16137

@borngraced

Description

@borngraced

What it does

Clippy should warn when a const, static, or let binding is defined as one integer type but immediately/ consistently cast to another type at usage sites without any usage of the original type.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=27b8ef8ff029f755d6c6ff4d1ea2fbbd

Advantage

  • Reduces noise from unnecessary casts
  • Makes intended usage clearer
  • More idiomatic when value is primarily/only used as a specific type

Drawbacks

No response

Example

fn op() {
    const SIZE: u16 = 15;

    let regs: [u16; SIZE as usize] = [0u16; SIZE as usize];
    let mem: [u16; SIZE as usize] = [0u16; SIZE as usize];
    // do something with regs/mem and return
}

Suggest defining with the target type directly:

help: consider defining this as `usize`
  |
1 | const SIZE: usize = 15;
  |            ~~~~~

Comparison with existing lints

No response

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions