rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

`cast_possible_wrap` could use a suggestion

Open yoav-lavi opened this issue 3 years ago • 0 comments

Description

cast_possible_wrap's docs currently have an explanation of why this isn't desirable, but do not give the user an alternative to use.

I'd like to suggest adding a mention of a safe method of converting between numeric types where the target is of a smaller size than the origin:

use std::convert::TryFrom;

let max_u32 = u32::MAX;
i32::try_from(max_u32).ok() // None, due to `u32::MAX` not fitting in an `i32`

let u32_value = 5_u32;
i32::try_from(u32_value).ok() // Some(5), since `5_u32` fits in an `i32`

Example Playground

Version

rustc 1.64.0-nightly (4d6d601c8 2022-07-26)
binary: rustc
commit-hash: 4d6d601c8a83284d6b23c253a3e2a060fd197316
commit-date: 2022-07-26
host: aarch64-apple-darwin
release: 1.64.0-nightly
LLVM version: 14.0.6

Additional Labels

No response

yoav-lavi avatar Jul 27 '22 09:07 yoav-lavi