Skip to content

Possible more DRY suggestion for "as" cast #13815

Open
@leonardo-m

Description

Description

I am not sure if this is a good idea or if it can be done. But I think it's worth reporting here.

I'm using v.1.85 Nightly from the Playground. This code:

#![allow(dead_code)]
#![warn(clippy::all)]
#![warn(clippy::nursery)]
#![warn(clippy::pedantic)]

fn test1(x: u32) -> u16 {
    x as u16
}
fn main() {}

Gives:

warning: this could be a `const fn`
 --> src/main.rs:6:1
  |
6 | / fn test1(x: u32) -> u16 {
7 | |     x as u16
8 | | }
  | |_^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#missing_const_for_fn
note: the lint level is defined here
 --> src/main.rs:3:9
  |
3 | #![warn(clippy::nursery)]
  |         ^^^^^^^^^^^^^^^
  = note: `#[warn(clippy::missing_const_for_fn)]` implied by `#[warn(clippy::nursery)]`
help: make the function `const`
  |
6 | const fn test1(x: u32) -> u16 {
  | +++++

warning: casting `u32` to `u16` may truncate the value
 --> src/main.rs:7:5
  |
7 |     x as u16
  |     ^^^^^^^^
  |
  = help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ...
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cast_possible_truncation
note: the lint level is defined here
 --> src/main.rs:4:9
  |
4 | #![warn(clippy::pedantic)]
  |         ^^^^^^^^^^^^^^^^
  = note: `#[warn(clippy::cast_possible_truncation)]` implied by `#[warn(clippy::pedantic)]`
help: ... or use `try_from` and handle the error accordingly
  |
7 |     u16::try_from(x)
  |

So replacing the "as" cast with try_from is safer, on the other hand, if the programmer wishes to keep the "as" cast, then an alternative more DRY (don't repeat yourself) way to write that code is:

#![allow(dead_code)]
#![warn(clippy::all)]
#![warn(clippy::nursery)]
#![warn(clippy::pedantic)]

fn test2(x: u32) -> u16 {
    x as _
}
fn main() {}

Sometimes it's better to write DRY code. It's also good for Clippy to show this syntax because it's less known than the common way to cast with "as".

Version


Additional Labels

No response

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions