Introduction
Rust is a strongly typed language. Hence the types of all variables used in a Rust program must be known during compile-time.
Data types again can be classified into two categories, Scalar and Sompound.
We'll start by discussing about Scalar data types.
Scalar Data Types
There are four such kinds:
intergers
floats
booleans
characters
You can consider it to be similar to primitive types in other languages.
Integers
Integers mean whole numbers. They can again be classified into signed & unsigned integers.
let x: u8 = 25;
let y: i16 = 89;
In the above code snippet x is an unsigned integer, and y is a signed integer. u8 means x is unsigned and can store 8-bits of memory. So it can be concluded that x is in between 0 and 2 ^ 8 - 1
On the otherhand i16 means that y is signed and can hold 16-bits of memory. So y is in between -2 ^ 8 and 2 ^ 8 - 1
We can have unsigned integers: u8, u16, u32, u64, u128
And unsigned integers: i8, i16, i32, i64, i128
Now if you let's say write:
let x: u8 = 334;
The compiler will panic! Because the maximum value of x than can be stored = 255 as discussed above. So you cannot store 334. This is called Integer Overflow
Floats
Floating-point numbers are nothing but Decimal numbers. And Rust only has two such types f32 & f64
This is how you can declare floats.
let x: f32 = 5.5;
let y: f64 = 6.4;
The default type is f64, for below case:
let z = 10.9;
Booleans
Booleans are true & false. The default type being true.
let x: bool = false;
let y = true;
Characters
Characters are basically letters. But we can also store emojis!
let x = 'x';
let y: char = 'y';
let z: char = '๐';
Compound Data Types
Compound data types are complex, they can store multiple data types together to form a new kind of data type.
Tuples
Tuples can store multiple data types inside parentheses () in comma , separated format.
Once declared they cannot grow or shrink in size.
let tup: (i8, u16, char) = (11, 2, 'x');
println!("{}", x.0); // 11
println!("{}", x.1); // 2
println!("{}", x.2); // x
Individual elements of a tuple can be accessed by using a dot .
Arrays
Arrays are another way to store a collection of values. But unlike tuples they can only store one data type.
let arr_num = [3, 5, 23, 12];
let arr_char = ['a', 'g', 'z'];
Arrays can also be declared in the below format:
let arr_num: [i32; 4] = [3, 5, 23, 12];
i32 is the data type, 4 is the number of elements.
let arr = [6; 4]; // [6, 6, 6, 6]
This is also another way to create arrays.
let arr = [1, 23, 12, 45, 2];
let a = arr[1]; // 23
let b = arr[4]; // 2
We can access array elements by their index using square brackets []
Conclusion
That's all in brief about Data Types in Rust. In the upcoming articles we'll learn how to effectively use them while writing Rust Programs. Cheers!