In this tutorial you will learn about the Rust Type Casting and its application with practical example.
Rust Type Casting
Type Casting is a mechanism which enables a variable of one datatype to be converted to another datatype.When a variable is typecast into a different type, the compiler basically treats the variable as of the new data type.
Rust provides no implicit type conversion (coercion) between primitive types. But, explicit type conversion (casting) can be performed using the as
keyword.
Type of casting
- implicit or automatic
- explicit or given
Implicit or automatic
In implicit or automatic casting compiler will automatically change one type of data into another. Rust provides no implicit type conversion (coercion) between primitive types. Coercion between types is implicit and has no specified syntax. Coercion is usually be seen in let
, const
, and static
statements; in function call arguments; in field values in struct initialization; and in a function result.
Example:-
The coercion can be used in removing mutability from a reference as following –
1 |
&mut T to &T |
Mutability of a raw pointer can removed as following –
1 |
*mut T to *const T |
A references can be coerced to raw pointers as follows –
1 2 |
&T to *const T &mut T to *mut T |
Explicit or given
In Rust, a variable can be explicitly type cast using the as
keyword. The as
keyword does safe casting. Typecasting should always be used in right order (low to higher datatype). Type casting in wrong places may result in loss of precision, which the compiler can signal with a warning.
Example:-
1 2 3 |
let a: i32 = 10; let b = a as i64; |
In Rust, type casting rules are same as of C Programming .