Scalar types are the building blocks of data in Rust, representing single values such as numbers, characters, and booleans. In this blog, we’ll explore the four primary scalar types in Rust: integers, floating-point numbers, Booleans, and characters. Understanding these types is crucial for effective programming in Rust, as they are foundational to working with data.
Integers
Integers in Rust come in two flavors: signed and unsigned. Each has different sizes, indicated by the number of bits they occupy in memory.
- Unsigned Integers:
u8
,u16
,u32
,u64
,u128
,usize
- These integers start with
u
(for unsigned) followed by the number of bits they use. usize
is unique as it represents the size of a pointer on the system, making it ideal for indexing arrays and vectors.
- These integers start with
- Signed Integers:
i8
,i16
,i32
,i64
,i128
,isize
- These integers start with
i
(for signed) and also vary by the number of bits.
- These integers start with
Integer Literals: Rust allows you to express integer literals in multiple formats:
- Decimal:
98_222
,1_000_000
(underscores for readability) - Hexadecimal:
0xff
- Octal:
0o77
- Binary:
0b1111_0000
- Byte (only for
u8
):b'A'
Floating-Point Numbers
Rust supports two types of floating-point numbers: f32
and f64
, where the number represents the bits of precision.
f32
: 32 bits of precisionf64
: 64 bits of precision (default type)
The choice of f64
as the default is due to its balance between speed and precision on modern CPUs. However, f64
can be slower on architectures with less than 64-bit support. All floating-point literals in Rust follow the IEEE-754 standard.
Examples:
1.0
(defaultf64
)1.0f64
(explicitf64
)1.0f32
(explicitf32
)
Note: .1
is not a valid float; it must be written as 0.1
.
Booleans
Booleans in Rust are represented by the bool
type, which can hold one of two values: true
or false
. These are the only two boolean literals available in Rust, making the type straightforward and easy to use.
Example:
let is_active: bool = true;
RustCharacter Types
Rust’s char
type is unique in that it represents a Unicode Scalar Value, which means it can store any valid Unicode character. Unlike many other languages, Rust’s char
type is four bytes in size, allowing it to handle a vast range of characters.
Examples:
'a'
(simple character)'ℤ'
(mathematical symbol)'😻'
(emoji)
It’s important to note that while strings in Rust are UTF-8 encoded, characters are not stored internally as char
. This distinction is critical when working with strings versus individual characters.
Conclusion
Understanding Rust’s scalar types is essential for writing efficient and safe code. These types—integers, floating-point numbers, Booleans, and characters—are the foundation of Rust’s data handling capabilities. Whether you’re performing arithmetic, managing logical conditions, or working with Unicode characters, mastering scalar types will enable you to harness the full power of Rust.