Type Conversion

Generally type conversion in RUST is where we convert in one values data type to another data type.

There are two kinds of Type Conversions.

  1. Explicitly One:  Where programmer explicitly mention the type change using keywords like asor using function like try_into()
  2. Implicit One:  when compiler automatically does the conversion when necessary

Explicit Conversion

We can use the keyword as for type conversion for example.

				
					let a: u32 = 23;
let b: f64 = a as f64;
				
			

We use try_into() function for cases where we are not sure the end result of the Type conversion and this will return a Result Type, which can be a converted value or the error.

				
					let x: u32 = 128;
// convert u32 to u8, may panic if overflow
let y: u8 = x.try_into().unwrap(); 
				
			

Implicit Conversion

The small integers are automatically promoted to larger integers when used in expressions by the complier.

				
					let a: u8 = 80;
// u8 automatically gets promoted to u32
let x: u32 = a + 120 ;
				
			

Other Type conversions

Integer to string

using to_string() function.

				
					let a:u32 = 36
let b:String = a.to_string();
				
			

Sting to Integer

				
					let a: String = "23".to_string();
// This can panic as this conversion can fail
let b: u32 = a.parse().unwrap();
				
			

Array to Vector

				
					let a: [u32, 5] = [12,32,34,19,90];
let b: Vec<u32> = a.to_vec();
				
			

Points to remember during Type conversion in RUST