Every value in Rust is of a certain data type, which tells Rust what kind of data is being specified so it knows how to work with it.
Scalar data type: Types that store only a single value.
Compound data type: Types that store multiple values, even values of different types.
Scalar Types
Rust has four primary scalar types: integers, floating-point numbers, Booleans, and characters.
Integers
Integers refer to whole numbers. Integers in Rust are either Signed or Unsigned. Unsigned integers store only 0 and positive numbers, while Signed integers can store negative numbers, 0 and positive numbers.
Following are the available Integer types based on the sign and length:
Each signed variant can store numbers from -(2n - 1) to 2n - 1 - 1 inclusive, where n is the number of bits that the variant uses. Unsigned variants can store numbers from 0 to 2n - 1.
Here is an example of an integer:
fn main() {
let x :u8 = "42"; // 8bit
let x :i16 = "21"; // 16 bit
let x :u32 = "43"; // 32 bit
let x :i64 = "32"; //64 bit
let x :u128 = "72"; // 128 bit
let x :usize = "98"; // depend on the architecture of the computer
}
Floating point numbers
Floating point numbers, more commonly known as float(s), are a data type that holds numbers that have a fractional value (something after the decimal point). Rust's floating-point types are f32
and f64
, 32 bits and 64 in size, respectively.
Here is an example that shows floating-point numbers:
fn main() {
let x = 2.0; // f64
let y: f32 = 3.0; // f32
}
Characters
You can store a single character in a variable, and the type is char
. Like traditional programming languages of the 80s, you can store an ASCII character. But Rust also extends the character type to store a valid UTF-8 character. This means that you can store an emoji in a single character ๐
Here is an example:
fn main() {
let a = 'a';
let p: char = 'p'; // with explicit type annotation
let crab = '๐ฆ';
}
Booleans
The boolean type in Rust stores only one of two possible values: true
or false
. If you wish to annotate the type, use bool
to indicate the type.
Here is an example:
fn main() {
let t = true;
let f: bool = false; // with explicit type annotation
}
Compound Types
Compound data types can store multiple values in a variable. These values may be of the same scalar data type or different scalar types. Rust has two primitive compound types: tuples and arrays.
The Tuple Type
A tuple stores multiple values, either of the same type or even of different types. Once declared, they cannot grow or shrink in size. We create a tuple by writing a comma-separated list of values inside parentheses.
Here is an example:
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
}
The Array Type
The Array Type stores multiple values of the same type. Unlike arrays in some other languages, arrays in Rust have a fixed length. We write the values in an array as a comma-separated list inside square brackets:
fn main() {
let a = [1, 2, 3, 4, 5];
}
Top comments (0)