]> git.lizzy.rs Git - rust.git/blob - src/docs/cast_lossless.txt
Auto merge of #9421 - xphoniex:fix-#9420, r=giraffate
[rust.git] / src / docs / cast_lossless.txt
1 ### What it does
2 Checks for casts between numerical types that may
3 be replaced by safe conversion functions.
4
5 ### Why is this bad?
6 Rust's `as` keyword will perform many kinds of
7 conversions, including silently lossy conversions. Conversion functions such
8 as `i32::from` will only perform lossless conversions. Using the conversion
9 functions prevents conversions from turning into silent lossy conversions if
10 the types of the input expressions ever change, and make it easier for
11 people reading the code to know that the conversion is lossless.
12
13 ### Example
14 ```
15 fn as_u64(x: u8) -> u64 {
16     x as u64
17 }
18 ```
19
20 Using `::from` would look like this:
21
22 ```
23 fn as_u64(x: u8) -> u64 {
24     u64::from(x)
25 }
26 ```