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

cast_possible_wrap could use a suggestion #9250

Open
yoav-lavi opened this issue Jul 27, 2022 · 0 comments
Open

cast_possible_wrap could use a suggestion #9250

yoav-lavi opened this issue Jul 27, 2022 · 0 comments

Comments

@yoav-lavi
Copy link
Contributor

yoav-lavi commented Jul 27, 2022

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

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