File tree Expand file tree Collapse file tree 1 file changed +20
-0
lines changed Expand file tree Collapse file tree 1 file changed +20
-0
lines changed Original file line number Diff line number Diff line change @@ -59,5 +59,25 @@ fn main() {
5959 println!("1000 as a u8 is : {}", 1000 as u8);
6060 // and the two's complement of 232 is -24
6161 println!(" 232 as a i8 is : {}", 232 as i8);
62+
63+ // Since Rust 1.45, the `as` keyword performs a *saturating cast* when casting from float to int.
64+ // If the floating point value exceeds the upper bound or is less than the lower bound, the returned value will be equal to the bound crossed.
65+
66+ // 300.0 is 255
67+ println!("300.0 is {}", 300.0_f32 as u8);
68+ // -100.0 as u8 is 0
69+ println!("-100.0 as u8 is {}", -100.0_f32 as u8);
70+ // nan as u8 is 0
71+ println!("nan as u8 is {}", f32::NAN as u8);
72+
73+ // This behavior incures a small runtime cost and can be avoided with unsafe methods:
74+ unsafe {
75+ // 300.0 is 44
76+ println!("300.0 is {}", 300.0_f32.to_int_unchecked::<u8>());
77+ // -100.0 as u8 is 156
78+ println!("-100.0 as u8 is {}", (-100.0_f32).to_int_unchecked::<u8>());
79+ // nan as u8 is 0
80+ println!("nan as u8 is {}", f32::NAN.to_int_unchecked::<u8>());
81+ }
6282}
6383```
You can’t perform that action at this time.
0 commit comments