In this article, we are going to learn How to Create an alias for the built-in data type Rust. This is the same as we have typedef in C and C++ languages. In Rust, we need to specify the details of the variables data types like i32 or i64. This becomes messy in the code so to handle this we prefer to use the aliases for good code visibility. We can use the “type” keyword.
What is the type keyword in Rust
type keyword is used to define an alias for an existing type. An important point to note here is that the type keyword in Rust does not create a new data type. It only creates a new name for existing data types for code writing purposes. The syntax to use the type keyword is:
type Name = ExistingType;.
How to use type keyword to create an alias in Rust
Let us see some of the examples of type keywords in action.In the below code example, we are creating two types of Meters and Kilograms one is of type u32 (unsigned 32 bit) and another one is i32(integer 32 bit). Then we are declaring two variables m and k and in this declaration, we are using our defined types instead of actual data types u32 and i32.
type Meters = u32;
type Kilograms = i32;
let m: Meters = 3;
let k: Kilograms = 3;
Let us see it with another full code working example
:
fn main()
{
type Int=i32;
let mut num:Int=1024;
println!("The Number is: {}",num);
}
Output
./main
The Number is: 1024