You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/types/cast.md
+20Lines changed: 20 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -59,5 +59,25 @@ fn main() {
59
59
println!("1000 as a u8 is : {}", 1000 as u8);
60
60
// and the two's complement of 232 is -24
61
61
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, however the results might overflow and return **unsound values**. Use these methods wisely:
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>());
0 commit comments