Casting

Rust provides no implicit type conversion (coercion) between primitive types. But, explicit type conversion (casting) can be performed using the as keyword.

Rules for converting between integral types follow C conventions generally, except in cases where C has undefined behavior. The behavior of all casts between integral types is well defined in Rust.

1. // Suppress all warnings from casts which overflow.
2. #![allow(overflowing_literals)]

4. fn main() {
5. let decimal = 65.4321_f32;

7. // Error! No implicit conversion
8. let integer: u8 = decimal;
9. // FIXME ^ Comment out this line

11. // Explicit conversion
12. let integer = decimal as u8;
13. let character = integer as char;

15. println!("Casting: {} -> {} -> {}", decimal, integer, character);

17. // when casting any value to an unsigned type, T,
18. // std::T::MAX + 1 is added or subtracted until the value
19. // fits into the new type

21. // 1000 already fits in a u16
22. println!("1000 as a u16 is: {}", 1000 as u16);

24. // 1000 - 256 - 256 - 256 = 232
25. // Under the hood, the first 8 least significant bits (LSB) are kept,
26. // while the rest towards the most significant bit (MSB) get truncated.
27. println!("1000 as a u8 is : {}", 1000 as u8);
28. // -1 + 256 = 255
29. println!("  -1 as a u8 is : {}", (-1i8) as u8);

31. // For positive numbers, this is the same as the modulus
32. println!("1000 mod 256 is : {}", 1000 % 256);

34. // When casting to a signed type, the (bitwise) result is the same as
35. // first casting to the corresponding unsigned type. If the most significant
36. // bit of that value is 1, then the value is negative.

38. // Unless it already fits, of course.
39. println!(" 128 as a i16 is: {}", 128 as i16);
40. // 128 as u8 -> 128, whose two's complement in eight bits is:
41. println!(" 128 as a i8 is : {}", 128 as i8);

43. // repeating the example above
44. // 1000 as u8 -> 232
45. println!("1000 as a u8 is : {}", 1000 as u8);
46. // and the two's complement of 232 is -24
47. println!(" 232 as a i8 is : {}", 232 as i8);
48. }