Rust Type Casting

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 –

Mutability of a raw pointer can removed as following –

A references can be coerced to raw pointers as follows –

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:-

In Rust, type casting rules are same as of C Programming .

Recommended:-  Rust Macros
In this tutorial we have learn about the Rust Type Casting and its application with practical example. I hope you will like this tutorial.