Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possible more DRY suggestion for "as" cast #13815

Open
leonardo-m opened this issue Dec 11, 2024 · 0 comments
Open

Possible more DRY suggestion for "as" cast #13815

leonardo-m opened this issue Dec 11, 2024 · 0 comments

Comments

@leonardo-m
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant