Casting in Rust Programming


Casting or explicit conversion is only allowed in Rust, there’s no implicit conversion that the compiler of Rust does for us. It is known that, in many cases, implicit conversion can lead to data losses, which is not a good thing.

Rules for converting between different types is pretty similar to C. In Rust though, we make use of as keyword when we want to convert from one type to another.

Example:

Consider the following example:

 Live Demo

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

fn main() {
   let decimal = 65.43_f32;

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

   // Explicit conversion
   let integer = decimal as u8;
   let character = integer as char;

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

In the above code example, we are trying to convert a float32 value into an integer and then that integer into a char, and then finally printing them out to the terminal.

Output

Casting: 65.43 -> 65 -> A

If we remove the comment on the implicit conversion, then the compiler will throw an error.

Example

Consider the updated code shown below:

 Live Demo

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

fn main() {
   let decimal = 65.43_f32;

   // Error! No implicit conversion
   let integer: u8 = decimal;
   
   // FIXME ^ Comment out this line
   // Explicit conversion

   let integer = decimal as u8;
   let character = integer as char;

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

Output

error[E0308]: mismatched types
--> src/main.rs:8:23
|
8| let integer: u8 = decimal;
| -- ^^^^^^^ expected `u8`, found `f32`
| |
| expected due to this

Since Rust 1.45, the ‘as’ keyword also performs a saturation cast, when we are converting a float into an int.

Example

Consider the code shown below as an example:

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

fn main() {
   // 300.0 is 255
   println!("301.0 is {}", 301.0_f32 as u8);
   // -100.0 as u8 is 0
   println!("-101.0 as u8 is {}", -101.0_f32 as u8);
   // nan as u8 is 0
   println!("nan as u8 is {}", f32::NAN as u8);
}

Output

301.0 is 255
-101.0 as u8 is 0
nan as u8 is 0

Updated on: 03-Apr-2021

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements