Rust Fundamentals: Building Blocks
8 min read
Rust Fundamentals: Building Blocks
Welcome to the second chapter of your Rust journey! We're moving past the initial setup and diving into the core concepts that form the foundation of any Rust program. Think of this as learning the alphabet before you start writing epic poems. We'll cover the essentials you'll use every single day as a Rust developer.
1. Variables and Mutability: Making Things Change
The Problem: Imagine you're building a checkout system for an online store. You need a way to store the total price of a customer's cart. This total will change as they add or remove items. How do you hold onto this changing value in your program?
The Solution: Variables! A variable is essentially a named storage location that holds a value. In many programming languages, you can change the value of a variable whenever you want. Rust, however, has a slightly different and safer approach.
By default, variables in Rust are immutable, which is a fancy way of saying they can't be changed once they're set.
fn main() {
let items_in_cart = 5;
println!("You have {} items in your cart.", items_in_cart);
// Try to add another item (this will cause an error!)
// items_in_cart = 6;
// println!("You now have {} items in your cart.", items_in_cart);
}If you try to run the commented-out code, the Rust compiler will give you a friendly but firm error. This is one of Rust's core safety features. It prevents you from accidentally changing values that you didn't intend to.
Making Things Change (Mutability)
But what if you do want to change a value, like our shopping cart total? This is where the mut keyword comes in. By adding mut before a variable name, you make it mutable, allowing its value to be changed.
fn main() {
let mut items_in_cart = 5;
println!("You have {} items in your cart.", items_in_cart);
items_in_cart = 6;
println!("You now have {} items in your cart.", items_in_cart);
}Now, our program works as expected! We can update the number of items in the cart.
Interesting Fact ✨: Rust's emphasis on immutability by default helps prevent a whole class of bugs common in other languages where data is unintentionally modified.
Shadowing
There's another cool trick you can do with variables in Rust called "shadowing". This allows you to declare a new variable with the same name as a previous variable. The new variable "shadows" the old one.
fn main() {
let spaces = " ";
let spaces = spaces.len();
println!("The number of spaces is: {}", spaces);
}Here, we first bind spaces to a string of three spaces. Then, we create a new variable, also named spaces, and bind it to the length of the original string. This is different from marking a variable as mut because we are creating a new variable, and we can even change the type of the value.
2. Data Types: Scalars and Compounds 🏷️
The Problem: Your program needs to work with different kinds of information: numbers, text, true/false values, and collections of data. How does Rust know what kind of data a variable holds and how to work with it?
The Solution: Data types! Every value in Rust has a specific data type, which tells the compiler how to interpret and use that data. Rust is a statically typed language, which means it must know the types of all variables at compile time.
Scalar Types
Scalar types represent a single value.
Integers: Whole numbers. They can be signed (can be negative) or unsigned (only positive). They also come in different sizes (e.g., 8-bit, 32-bit, 64-bit). The most common is
i32(a 32-bit signed integer).rustlet age: u32 = 30; // Unsigned 32-bit integer let temperature: i8 = -5; // Signed 8-bit integerFloating-Point Numbers: Numbers with a decimal point. The two primary types are
f32andf64.f64is the default and is generally what you should use.rustlet pi: f64 = 3.14159;Booleans: Can be either
trueorfalse.rustlet is_rust_awesome: bool = true;Characters: A single Unicode character, denoted by single quotes.
rustlet initial: char = 'J'; let emoji: char = '🦀';
Compound Types
Compound types can group multiple values into one type.
Tuples: A fixed-size collection of values of different types. Think of them as a small, ad-hoc struct.
rustlet user_info: (&str, u32, bool) = ("Alice", 30, true); // Accessing tuple elements let name = user_info.0; let age = user_info.1; println!("{} is {} years old.", name, age);Arrays: A fixed-size collection of values of the same type.
rustlet days_of_week: [&str; 7] = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; // Accessing array elements let first_day = days_of_week[0]; println!("The first day of the week is {}.", first_day);
Under the Hood: The reason for different integer sizes (i8, i16, i32, i64, i128) is all about memory. A smaller integer type uses less memory. For most modern computers, i32 is a good default as it's generally the fastest.
3. Functions: Reusable Blocks of Code
The Problem: You find yourself writing the same piece of code over and over again. For instance, calculating the sales tax for different items. This is repetitive and makes your code harder to maintain.
The Solution: Functions! A function is a named block of code that performs a specific task and can be called from other parts of your program.
You've already been using a function: main(). This is the entry point for every Rust program.
Here's how you define a function:
fn main() {
greet_user("Alice");
let total_cost = calculate_total(100.0, 0.07);
println!("The total cost is: ${}", total_cost);
}
// A function that takes a parameter but doesn't return a value
fn greet_user(name: &str) {
println!("Hello, {}!", name);
}
// A function that takes parameters and returns a value
fn calculate_total(price: f64, tax_rate: f64) -> f64 {
let tax = price * tax_rate;
price + tax // This is an expression, and it's what gets returned
}Key Concepts:
- Parameters: Inputs to a function (e.g.,
name,price,tax_rate). - Return Value: The output of a function, specified with
->. - Statements vs. Expressions:
- Statements are instructions that perform some action and do not return a value. For example,
let x = 5;. - Expressions evaluate to a resulting value. For example,
5 + 6. In Rust, the last expression in a function is what gets returned, so you don't need to use thereturnkeyword.
- Statements are instructions that perform some action and do not return a value. For example,
Industry Practice: Keep your functions small and focused on a single task. This makes them easier to test, debug, and reuse.
4. Control Flow: If, Else, and Loops 🔀
The Problem: Your program needs to make decisions. For example, if a user is logged in, show them their dashboard; otherwise, show them the login page. You also need to perform repetitive tasks, like processing every item in a shopping cart.
The Solution: Control flow expressions! These allow you to control the order in which your code is executed.
if, else if, else
These expressions allow you to run different blocks of code based on a condition.
fn main() {
let age = 18;
if age >= 21 {
println!("You can enter the club.");
} else if age >= 18 {
println!("You can vote, but you can't enter the club yet.");
} else {
println!("You're too young for most things.");
}
}Because if is an expression in Rust, you can use it on the right side of a let statement.
fn main() {
let is_logged_in = true;
let message = if is_logged_in {
"Welcome back!"
} else {
"Please log in."
};
println!("{}", message);
}Loops
Rust has a few different kinds of loops for repeating code.
loop: An infinite loop. You'll need to use thebreakkeyword to get out of it.rustlet mut count = 0; loop { println!("Again!"); count += 1; if count == 5 { break; } }while: This loop will run as long as a condition is true.rustlet mut number = 3; while number != 0 { println!("{}!", number); number -= 1; } println!("LIFTOFF!!!");for: The most common and safest loop in Rust. It's used to iterate over a collection of items, like an array or a range.rustlet a = [10, 20, 30, 40, 50]; for element in a { println!("The value is: {}", element); } // A for loop with a range for number in 1..4 { // This will go from 1 to 3 println!("{}!", number); }
Funny Exaggeration 😂: Without loops, a programmer's life would just be Ctrl+C and Ctrl+V. Imagine having to copy and paste the code to process every single pixel in an image!
Further Reading
Challenge
You are tasked with creating an inventory analysis function for a small warehouse. Your goal is to process a fixed-size list of products and return key statistics.
Requirements:
Function Signature:
- Create a function named
calculate_inventory_stats. - This function must accept one parameter: an array containing exactly 4 tuples.
- Each tuple represents a product with the following data types in this specific order: a product ID (
u32), a price (f64), a quantity (u8), and its stock status (bool).
- Create a function named
Function Logic:
- Initialize two mutable variables: one to track the total monetary value of all in-stock items and another to count the number of product types that are out of stock.
- Use a
forloop to iterate through the input array. - Inside the loop, use an
ifexpression to check if a product is in stock (true).- If it is, add its total value (price * quantity) to your total value tracking variable.
- If it is not, increment your out-of-stock item counter.
Shadowing Demonstration:
- After the loop, create a variable to hold the total value in cents, calculated by multiplying the float total value by
100.0. - Immediately after, you must "shadow" this variable by declaring a new variable with the exact same name, which holds the value from the previous step cast as a
u64integer.
- After the loop, create a variable to hold the total value in cents, calculated by multiplying the float total value by
Return Value:
- The function must implicitly return a tuple containing two values in this order: the final total value of in-stock items (
f64) and the total count of out-of-stock item types (u32).
- The function must implicitly return a tuple containing two values in this order: the final total value of in-stock items (
Main Function:
- In the
mainfunction, create a sample inventory array that conforms to the required structure and size. - Call your
calculate_inventory_statsfunction with your sample data.
- In the
Expected result
Your final code should consist of two functions: main and calculate_inventory_stats.
The calculate_inventory_stats function must:
- Have the correct signature, accepting an array of type
[(u32, f64, u8, bool); 4]and returning a tuple of type(f64, u32). - Correctly initialize and use mutable
letbindings for the total value and out-of-stock count. - Use a
forloop to iterate over the array elements. - Use
if/elseconditional logic to correctly process items based on their stock status. - Perform the calculation
price * quantityfor in-stock items, correctly handling floating-point arithmetic. - Demonstrate the concept of shadowing on a variable after the loop concludes.
- Return the final results as a tuple using Rust's implicit return syntax (no
returnkeyword).
The main function must:
- Declare and initialize an array of 4 tuples that matches the specified data structure.
- Make a valid call to the
calculate_inventory_statsfunction, passing the created array as an argument.