Each programming language has its primitive data types. These primitive data types are also known as built-in types, which work as the base building blocks in every program. A data type is metadata, which means that a data type specifies what kind of data a variable is allowed to store in it.
Rust has its own primitive data types, just like other programming languages. Here is a list of the built-in data types in Rust:
i8
, i16
, i32
, i64
, u8
, u16
, u32
, u64
)f32
, f64
)This is the syntax that is used to declare a variable along with its data type:
let variable_name: <datatype> = Data_Value;
Each of the data types has its own rules and restrictions, which should be followed whenever we use them. Let’s look at the code example given below, which adds two numbers to see these restrictions in action:
// Main functionfn main(){let number1 = 5; // change this to a float ORlet number2 = 2.2; // change this to an integerprintln!("Number1 is : {}", number1);println!("Number2 is : {}", number2);println!("Number1+Number2 is equal to : {}", number1+number2)}
The program failed to run in the code widget above. The reason behind this failure is the data type of both the variables. However, the values of both the variables are numbers and we didn’t specify their data types, so why is the program throwing an error?
To get rid of this error, we will change the value of number2
to an integer, or change number1
to a float type. Once the variables are of the same data type, the code will sum them up.
Whenever we declare a variable without specifying its data type, Rust automatically specifies the variable’s data type according to its input type.
// Main functionfn main(){let number1: i32 = 5; // change to i64 ORlet number2: i64 = 2; // change to i32println!("Number1 is : {}", number1);println!("Number2 is : {}", number2);println!("Number1+Number2 is equal to : {}", number1+number2)}
In the code given above, we use the integer data type for the both variables, but Rust still throws an error. This is because Rust never performs arithmetic operations on variables that belong to non-identical data types or offshoots of identical data types.
To get rid of the error in the code, we will change the data type of number2
from i64
to i32
, or vice versa for number1
.
Free Resources