Learn about the different data types Rust offers.
Being a statically typed language, Rust requires that every variable's type is known at compile time.
Being a statically typed language, Rust requires that every variable's type is known at compile time.
To specify a variable's type, you'd add a type annotation like this:
// Here, we're specifying that `flag` is of type `bool`
let flag: bool = true;
In many cases, a type annotation might not be required. The Rust compiler is clever; it can infer the type we intend to use based on the value and how it's used.
// Here the compiler infers 'flag' is a bool due to its value being 'true'
let flag = true;
A scalar type represents a single value.
Rust has 4 scalar types — integers, floating-point numbers, booleans, and characters.
let x = 42; // Integer
let x = 4.2; // Float
let x = true; // Boolean
let x = 'a'; // Char
We'll cover these 4 types in detail in later concepts.
Compound types group multiple values into a single type.
The two primary compound types in Rust are tuples and arrays. Here's a quick overview:
// This is a tuple. It can group multiple values of different types.
let chess_square = (5, 'A');
// This is an array. It can group multiple values of the same type.
let array_of_ints = [1, 2, 3];
We'll learn more about tuples and arrays in later concepts.
For a deeper dive into Rust's data types, you can refer to the Rust book.