Polyglot CheatSheet - Type Casting and Type Conversion
Last Updated: 2022-04-04
Type Casting vs Type Conversion
- type conversion / type coercion: implicit, made automatically by compiler.
- type casting: explicit, done by the programmer using a cast operator.
Type Casting
C++
Read more: C++ Type Casting
Rust
Explicit type conversion (casting) can be performed using the as
keyword.
let integer = decimal as u8;
Saturating cast: when casting from float to int. 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.
// result is 255
300.0_f32 as u8
// result is 0
-100.0_f32 as u8
// result is 0
f32::NAN as u8
Use unsafe
to bypass this, but may overflow:
unsafe {
// result is 44
300.0_f32.to_int_unchecked::<u8>()
// result is 156
(-100.0_f32).to_int_unchecked::<u8>()
}