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)]
  3. fn main() {
  4. let decimal = 65.4321_f32;
  5. // Error! No implicit conversion
  6. let integer: u8 = decimal;
  7. // FIXME ^ Comment out this line
  8. // Explicit conversion
  9. let integer = decimal as u8;
  10. let character = integer as char;
  11. println!("Casting: {} -> {} -> {}", decimal, integer, character);
  12. // when casting any value to an unsigned type, T,
  13. // std::T::MAX + 1 is added or subtracted until the value
  14. // fits into the new type
  15. // 1000 already fits in a u16
  16. println!("1000 as a u16 is: {}", 1000 as u16);
  17. // 1000 - 256 - 256 - 256 = 232
  18. // Under the hood, the first 8 least significant bits (LSB) are kept,
  19. // while the rest towards the most significant bit (MSB) get truncated.
  20. println!("1000 as a u8 is : {}", 1000 as u8);
  21. // -1 + 256 = 255
  22. println!(" -1 as a u8 is : {}", (-1i8) as u8);
  23. // For positive numbers, this is the same as the modulus
  24. println!("1000 mod 256 is : {}", 1000 % 256);
  25. // When casting to a signed type, the (bitwise) result is the same as
  26. // first casting to the corresponding unsigned type. If the most significant
  27. // bit of that value is 1, then the value is negative.
  28. // Unless it already fits, of course.
  29. println!(" 128 as a i16 is: {}", 128 as i16);
  30. // 128 as u8 -> 128, whose two's complement in eight bits is:
  31. println!(" 128 as a i8 is : {}", 128 as i8);
  32. // repeating the example above
  33. // 1000 as u8 -> 232
  34. println!("1000 as a u8 is : {}", 1000 as u8);
  35. // and the two's complement of 232 is -24
  36. println!(" 232 as a i8 is : {}", 232 as i8);
  37. }