Skip to content

Commit 1524759

Browse files
authored
Merge pull request #1384 from sakex/master
Add 1.45.0 cast documentation
2 parents 7d3ff1c + 1331757 commit 1524759

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/types/cast.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff 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, 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>());
81+
}
6282
}
6383
```

0 commit comments

Comments
 (0)