Rust has two main sets of data types for variables: scalar and compound.
Scalar variables are those that can store a single value at a time. There are four scalar data types in Rust.
An integer is a numerical value that does not have a fractional part. An integer can be signed or unsigned. A signed integer (i
) can store a negative or a positive value, whereas an unsigned integer (u
) can only store positive values. The number of bits used by an integer is explicitly mentioned and is a part of the data type’s name. For example, a variable of type i8
is a signed integer that uses 8 bits.
isize
andusize
are two special types of integers that are 32-bits or 64-bits depending on the architecture of the CPU.
When no size is explicitly mentioned, i32
is used by default. For example:
let x = 1; // Equivalent to x: i32 = 1;
let y: u64 = 12 // u64
Rust offers floating-point types f32
(32-bit size) and f64
(64 bit-size) to store numbers that have a decimal value. If no size is explicitly mentioned, f64
is used by default:
let x = 1.0; // f64
let y: f32 = 12.5; // f32
Similar to other languages, Rust has a boolean data type that can store either true
or false
as its value. The bool
keyword is used to specify this scalar data type. A value of true
or false
can also be stored in a variable without using this keyword:
let b = true; // Equivalent to b: bool = true;
In addition to strings, Rust also supports a character data type. Unlike most other programming languages, a character in Rust has a size of 4 bytes instead of 1, and it represents a Unicode Scalar Value meaning that it can store more than just an alphabet (Japanese characters, emojis, accented letters, etc.). A char
value is stored using single quotes:
let x = 'R';
Free Resources