Rust-clippy: lint unnecessary literal casts

Created on 5 Oct 2020  路  8Comments  路  Source: rust-lang/rust-clippy

What it does

Lints unnecessary as-casts of literals when they could be written using literal syntax.

Categories (optional)

  • Kind: clippy::style

What is the advantage of the recommended code over the original code

  • Avoids accidental truncation
  • Uses syntax dedicated to this purpose

Drawbacks

None.

Example

1 as u32

Could be written as:

1u32
A-suggestion L-lint good-first-issue hacktoberfest

Most helpful comment

Hi, I'd be glad to give this a shot !

All 8 comments

Better to suggest: 1_u32

This would be currently linted by as_conversions (playground). The docs imply it's allow-by-default because it has false positives.

The lint could be improved though to generate suggestions as the one you gave.

I think the lints serve different purposes. I 1 as u32 is almost certainly a mistake, while there are legitimate uses of as casts in general (which is why it's allow-by-default).

Yes as_conversions is a restriction lint, with the design that it lints all as conversions, regardless what it converts.

Hi, I'd be glad to give this a shot !

When testing my implementation, I noticed that there is some overlap with a previously existing lint that flags int literals that are casted to a float type.

Would it be suitable to just extend the aforementioned lint so that it become "casting number literal to is unnecessary" ? If not, what would be a good way to handle the overlap ?

@geoffreycopin I think what you suggest makes sense as that lint was already extended in #3842 to add the float cases.

Even if later there's a decision to not enhance that lint, your code should go in that module to be able to handle the overlap.

Fixed by #6187

Was this page helpful?
0 / 5 - 0 ratings