“Certified Rust Programming Expert” – A complete path from beginner to professional
Welcome back, future Rust expert! In Module One, you learned how to install Rust, write your first program, and use variables and functions. You made the computer talk with println!. You also learned how to read input from the user.
But a program that only runs straight from top to bottom is boring. Real programs need to make decisions and repeat things. Imagine a traffic light that never changes, or a game that never checks if you won. That would be useless!
In this module, we will learn two superpowers: decision making (using if, else, and match) and repeating actions (using loops). We will also learn about Rust’s most special idea: ownership. This is what makes Rust safe and fast. Don’t worry—we will use simple stories, examples from Nigeria, and lots of pictures made with text.
By the end, you will be able to write programs that think and act, just like a smart robot. And you will understand how Rust manages memory without a garbage collector. Let’s begin!
After finishing this module, you will be able to:
if, else if, and else to make decisions in Rust.match to compare a value against many patterns.loop, while, and for to repeat actions.& and mutable borrowing with &mut.Remember Ada and her robot Chidi from Module One? After Ada learned Rust, she rebuilt Chidi’s brain. Now Chidi could walk without crashing. But Chidi still had a problem: Chidi did not know when to stop walking!
One day, Ada took Chidi to the market in Lagos. Chidi was supposed to follow Ada and stop when she stopped. But Chidi just kept walking. Ada shouted, “Chidi, stop!” But Chidi did not understand.
Ada realized that Chidi needed to make decisions. Chidi needed to check: “Is Ada in front of me? If yes, keep walking. If no, stop.” Chidi also needed to repeat this check many times, like a loop.
So Ada wrote a new program using if and while. She taught Chidi to check Ada’s position again and again. Now Chidi could decide when to walk and when to stop.
But there was another problem. Chidi kept losing track of Ada’s bag. When Ada gave the bag to Chidi to carry, Chidi would drop it because Chidi thought Ada still had it. Ada explained, “Chidi, when you take the bag, you own it. I don’t own it anymore. That is called ownership.”
Chidi learned about ownership. Now Chidi could carry the bag safely without dropping it. Chidi became the smartest robot in Lagos!
Moral of the story: Programs need to make decisions and repeat actions to be useful. And they need ownership to manage things safely. Rust gives us tools like if, match, loops, and ownership to do this.
ifDefinition: if is a keyword that runs a block of code only when a condition is true.
Why it is important: Programs need to choose different actions in different situations. if lets them do that.
Simple explanation: Imagine you are hungry. You check: “If I am hungry, I will eat.” The action (eating) only happens if the condition (hungry) is true.
Real-life example: A traffic light: if the light is red, cars stop. If green, cars go.
School example: If you score above 50, you pass the exam. If not, you fail.
Home example: If the pot is hot, use a cloth to hold it. If not, hold it directly.
Nigerian example: If it rains in Lagos, take an umbrella. If not, leave it at home.
Illustration:
let hungry = true;
if hungry {
println!("Time to eat!");
}
Step-by-step:
if followed by a condition.bool (true or false).{ and close with }.Mini summary: if runs code only when a condition is true. It is the first step to making your program smart.
else and else ifDefinition: else runs when the if condition is false. else if checks another condition if the first one is false.
Why it is important: Sometimes you need more than two choices. else if lets you check many conditions in order.
Simple explanation: If you are hungry, eat. Else if you are thirsty, drink. Else, rest.
Real-life example: A grading system: if score >= 70, grade A; else if score >= 60, grade B; else, grade C.
School example: If it is Monday, wear uniform. Else if it is Friday, wear sports wear. Else, wear casual.
Home example: If there is rice, cook rice. Else if there is beans, cook beans. Else, order food.
Nigerian example: If there is fuel, drive the car. Else if there is diesel, use the generator. Else, take a bus.
Illustration:
let score = 75;
if score >= 70 {
println!("Grade A");
} else if score >= 60 {
println!("Grade B");
} else {
println!("Grade C");
}
Mini summary: else if lets you check many conditions. else catches everything else. Use them together for smart decisions.
Definition: A condition is an expression that is either true or false. Boolean logic uses && (AND), || (OR), and ! (NOT).
Why it is important: You often need to check more than one thing at once.
Simple explanation: && means both must be true. || means at least one must be true. ! flips true to false and false to true.
Real-life example: You can ride a bike if you have a helmet AND you know how to ride.
School example: You can go to the library if you have a library card OR a teacher’s note.
Home example: You can watch TV if you have finished homework AND it is not too late.
Nigerian example: You can travel if you have your ticket AND your luggage is ready.
Illustration:
let has_helmet = true;
let knows_riding = false;
if has_helmet && knows_riding {
println!("You can ride!");
} else {
println!("Not yet safe to ride.");
}
if !knows_riding {
println!("You need to learn riding first.");
}
Mini summary: Use &&, ||, and ! to combine or flip conditions. They make your decisions more powerful.
match Expression – A Better Way to ChooseDefinition: match compares a value against many patterns and runs the code for the matching pattern.
Why it is important: It is cleaner and safer than many if else blocks. Rust checks that you cover all possibilities.
Simple explanation: Imagine a vending machine. You press a button (A1, B2, C3). The machine matches your button to a snack. match does the same with values.
Real-life example: A traffic light: match the colour to an action. Red -> stop, Yellow -> ready, Green -> go.
School example: Match the day of the week to the subject: Monday -> Maths, Tuesday -> English, etc.
Home example: Match the weather to what you wear: Sunny -> T-shirt, Rainy -> raincoat.
Nigerian example: Match the market day to the market you visit: Monday -> Oshodi, Wednesday -> Mile 12, etc.
Illustration:
let light = "red";
match light {
"red" => println!("Stop!"),
"yellow" => println!("Get ready..."),
"green" => println!("Go!"),
_ => println!("Unknown light"),
}
Step-by-step:
match followed by the value.{ }, write patterns with => and code._ as the “catch-all” pattern for anything else.Mini summary: match is a clean way to choose between many options. It forces you to think of all cases.
loopDefinition: loop repeats a block of code forever until you tell it to stop with break.
Why it is important: Some tasks need to repeat many times, like checking for input or counting.
Simple explanation: Imagine a fan that keeps spinning until you press the off button. loop is like that fan. break is the off button.
Real-life example: A washing machine repeats the wash cycle until the timer ends.
School example: The school bell rings every day at the same time. It is a loop.
Home example: Your alarm clock rings every morning until you turn it off.
Nigerian example: A generator keeps running until you switch it off. loop is the generator, break is the switch.
Illustration:
let mut count = 0;
loop {
println!("Count is {}", count);
count += 1;
if count == 5 {
break;
}
}
Mini summary: loop repeats forever. Use break to stop. Be careful not to create an infinite loop by mistake!
while Loops – Repeat While TrueDefinition: A while loop repeats as long as a condition is true.
Why it is important: It is perfect when you don’t know how many times to repeat, but you know when to stop.
Simple explanation: While you are hungry, keep eating. When you are full, stop.
Real-life example: While the traffic light is red, cars wait. When it turns green, they go.
School example: While the teacher is talking, students listen. When the bell rings, they go out.
Home example: While the water is boiling, watch the pot. When it boils, turn off the stove.
Nigerian example: While there is fuel in the generator, it runs. When the fuel finishes, it stops.
Illustration:
let mut number = 3;
while number != 0 {
println!("{}!", number);
number -= 1;
}
println!("Liftoff!");
Mini summary: while checks a condition before each repeat. When the condition becomes false, the loop stops.
for Loops – Repeat a Known Number of TimesDefinition: A for loop repeats once for each item in a collection (like a range of numbers).
Why it is important: It is the safest and most common loop in Rust. It avoids mistakes with counters.
Simple explanation: For each day of the week, go to school. For each item in your bag, take it out.
Real-life example: For each passenger on a bus, collect the fare.
School example: For each student in the class, mark attendance.
Home example: For each plate in the sink, wash it.
Nigerian example: For each customer in the market, greet them “Welcome o!”.
Illustration:
for number in 1..5 {
println!("Number is {}", number);
}
let names = ["Ada", "Tunde", "Chidi"];
for name in names.iter() {
println!("Hello, {}!", name);
}
Mini summary: for loops go through each item. They are clean and safe. Use them when you know the collection.
Definition: An expression produces a value. A statement performs an action but produces no value.
Why it is important: Rust is an expression-based language. Many things are expressions, like if and match.
Simple explanation: 5 + 3 is an expression (it gives 8). let x = 5; is a statement (it does something but gives nothing).
Real-life example: “What is 2+2?” is an expression (answer 4). “Close the door” is a statement (action, no value).
School example: “What is your name?” (expression, answer). “Raise your hand” (statement, action).
Home example: “How many eggs?” (expression). “Put the eggs in the basket” (statement).
Nigerian example: “How much is the yam?” (expression). “Buy the yam” (statement).
Illustration:
let x = 5; // statement
let y = { // block expression
let a = 3;
a + 1 // no semicolon, so it is the value
};
println!("y is {}", y); // prints 4
Mini summary: Expressions give values. Statements do actions. In Rust, if and match can be expressions if you use them that way.
if in a let – Expressions in ActionDefinition: You can assign the result of an if or match expression to a variable.
Why it is important: It makes code shorter and cleaner.
Simple explanation: Instead of writing a long if else to set a variable, you can do it in one line.
Real-life example: “If it is sunny, wear sunglasses; else, wear a raincoat.” Assign that choice to “what to wear”.
School example: “If score is above 50, result is Pass; else, Fail.” Assign to “result”.
Home example: “If there is milk, breakfast is cereal; else, breakfast is bread.” Assign to “breakfast”.
Nigerian example: “If there is petrol, drive the car; else, take a bus.” Assign to “transport”.
Illustration:
let score = 75;
let result = if score >= 50 { "Pass" } else { "Fail" };
println!("Result: {}", result);
Mini summary: if and match can give values. Assign them to variables for cleaner code. Remember: no semicolon inside the block if you want the value.
Definition: Ownership is Rust’s system for managing memory. Each value has a single owner. When the owner goes out of scope, the value is dropped (freed).
Why it is important: It prevents memory bugs and makes Rust safe without a garbage collector.
Simple explanation: Imagine you have a toy. Only one person can own it at a time. If you give it to a friend, you no longer own it. Rust does the same with data.
Real-life example: A book in the library. Only one person can borrow it at a time. When returned, someone else can borrow it.
School example: A class monitor holds the attendance book. If they give it to another student, they no longer have it.
Home example: The TV remote. If you pass it to your sister, you cannot change the channel anymore.
Nigerian example: A single mobile phone. If you give it to your friend to make a call, you cannot use it until they return it.
Illustration:
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2. s1 is no longer valid.
// println!("{}", s1); // ERROR: s1 no longer owns the data
println!("{}", s2); // OK
Step-by-step:
Mini summary: Ownership means one owner at a time. When you assign a String to another variable, the original is moved. This prevents double-free errors.
Definition: Borrowing lets you use a value without taking ownership. You use & to create a reference.
Why it is important: It lets functions use data without stealing it from the owner.
Simple explanation: You can let a friend look at your book without giving it away. They borrow it and give it back.
Real-life example: A library book you read in the library. You don’t own it, but you can read it.
School example: You borrow a pencil from a friend. You use it and return it.
Home example: You borrow your brother’s charger. You use it and give it back.
Nigerian example: You borrow a pot from your neighbour to cook. You return it after.
Illustration:
fn main() {
let s = String::from("hello");
let len = calculate_length(&s); // borrow s
println!("The length of '{}' is {}.", s, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
Step-by-step:
& before a variable to borrow it.&Type as a parameter.Mini summary: Borrowing uses & to reference a value without moving it. The owner keeps ownership. This is safe and efficient.
Definition: You can borrow a value mutably with &mut if you want to change it.
Why it is important: Sometimes you need to modify data without taking ownership.
Simple explanation: You borrow a friend’s notebook and write in it with their permission.
Real-life example: A teacher borrows your homework to correct it. They can write on it (with permission).
School example: You borrow the class register to add your name. You need permission.
Home example: You borrow your mum’s phone to add a contact. She must allow it.
Nigerian example: You borrow a trader’s ledger to record a sale. The trader must agree.
Illustration:
fn main() {
let mut s = String::from("hello");
change(&mut s);
println!("{}", s); // prints "hello, world"
}
fn change(s: &mut String) {
s.push_str(", world");
}
Step-by-step:
let mut.&mut variable to the function.&mut Type.Mini summary: Use &mut to borrow and change. You can only have one mutable borrow at a time. This prevents data races.
Definition: A lifetime is how long a reference is valid. Rust uses lifetimes to prevent dangling references.
Why it is important: Lifetimes ensure that references are always safe to use.
Simple explanation: Imagine borrowing a book from a friend. You can only use it while your friend is still around. If your friend leaves, you cannot use the book. Lifetimes track this.
Real-life example: A library book has a due date. After that, you must return it.
School example: You can only use the school library while the library is open.
Home example: You can only use your brother’s charger while he is at home.
Nigerian example: You can only use a borrowed generator while the owner is still in town.
Illustration:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let s1 = String::from("hello");
let s2 = String::from("hi");
let result = longest(&s1, &s2);
println!("Longest: {}", result);
}
Step-by-step:
'a to name a lifetime.&'a str.Mini summary: Lifetimes track how long references are valid. They prevent dangling references. Rust often infers them automatically.
Definition: Mistakes (bugs) happen. Knowing them helps you avoid them.
Why it is important: Rust’s compiler catches many mistakes. Learn from the messages.
Simple explanation: Like learning to ride a bike, you may wobble. Rust helps you stay balanced.
Real-life example: Forgetting to turn off the tap. Rust checks that you don’t leave memory leaks.
School example: Forgetting to carry your homework. Rust checks that you don’t forget variables.
Home example: Forgetting to lock the door. Rust checks that your data is safe.
Nigerian example: Forgetting your change in a taxi. Rust checks that you don’t lose data.
Table of common mistakes:
| Mistake | What happens | Rust’s help |
|---|---|---|
| Using a moved value | Value no longer valid | Compiler error: “value borrowed after move” |
| Multiple mutable borrows | Data race possible | Compiler error: “cannot borrow as mutable more than once” |
Missing _ in match | Not all cases covered | Compiler error: “non-exhaustive patterns” |
Infinite loop without break | Program never stops | You must add a break condition |
Using == with different types | Type mismatch | Compiler error |
Forgetting mut for mutable borrow | Cannot borrow as mutable | Compiler error |
Mini summary: Rust catches many mistakes early. Read the error messages. They tell you exactly what to fix.
Let’s write a program that uses everything we learned: if, match, loops, and borrowing.
Program: Guess the Number (simplified)
use std::io;
fn main() {
let secret = 7;
let mut attempts = 0;
loop {
println!("Guess a number between 1 and 10:");
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("Failed to read");
let guess: i32 = guess.trim().parse().expect("Not a number");
attempts += 1;
if guess == secret {
println!("You win! You took {} attempts.", attempts);
break;
} else if guess < secret {
println!("Too low!");
} else {
println!("Too high!");
}
}
}
Explanation:
loop repeats until the correct guess.if else if else checks the guess.break exits the loop when correct.String::new() creates a new string.parse() converts text to a number.trim() removes extra spaces.Mini summary: This program combines decisions, loops, and input. You can build it and play!
| Word | Simple Definition |
|---|---|
| Control flow | The order in which code runs. Decisions and loops change it. |
if | Runs code when a condition is true. |
else | Runs code when the if condition is false. |
else if | Checks another condition if the first is false. |
match | Compares a value to many patterns. |
loop | Repeats forever until break. |
while | Repeats while a condition is true. |
for | Repeats for each item in a collection. |
| Expression | Produces a value. |
| Statement | Performs an action, no value. |
| Ownership | Each value has one owner. When owner goes away, value is dropped. |
| Borrowing | Using a value without taking ownership (&). |
| Mutable borrow | Borrowing to change (&mut). |
| Move | Transferring ownership from one variable to another. |
| Lifetime | How long a reference is valid. |
| Scope | The part of code where a variable is valid. |
if and else use bool values.match is powerful and safe.loop, while, and for repeat actions.if and match can give values.& to reference without moving. Use &mut to change.match step by stepmatch value {.=> and the code to run._ if needed.}.Example:
let day = "Monday";
match day {
"Monday" => println!("Start of week"),
"Friday" => println!("Almost weekend"),
_ => println!("Just another day"),
}
fn my_func(s: &String).&my_variable.Example:
fn main() {
let s = String::from("hello");
print_length(&s);
println!("Still own: {}", s);
}
fn print_length(s: &String) {
println!("Length: {}", s.len());
}
let mut s = String::from("hello");.&mut String.&mut s.match to decide stop, ready, or go.if to check if PIN is correct.loop to keep the game running until you quit.for to play each song in a playlist.while to keep asking until valid input.if to check if card is valid.match to decide when to stop and go.while to keep selling while there is stock.for to play each episode.loop to keep running until fuel finishes.if checks if you won or lost.while keeps the robot moving while battery is full.loop keeps the app running until you close it.for plays each song in your playlist.match checks your answer against the correct one.while time is not up, keep ringing.for each second, count down.match colour to action.if PIN is correct, allow withdrawal.for each tap, show letter.match keyword is one of Rust’s most loved features.for loop is safer than C’s for loop.match must cover every possible case?loop can return a value with break?if, else if, and else make decisions.match compares against many patterns.loop repeats forever; use break to stop.while repeats while a condition is true.for repeats for each item in a collection.& to reference, &mut to change.break in a loop._ in match.= instead of == in conditions.if conditions must be bool.for loops over while when possible.match instead of long if else chains.cargo check often.cargo fmt.cargo test.
Start
|
V
Is condition true? --Yes--> Run if block
|
No
|
V
Is else if condition true? --Yes--> Run else if block
|
No
|
V
Run else block
|
V
End
Start
|
V
Check condition (while) or enter loop
|
+--> Condition false? --> Exit loop
|
+--> Condition true? --> Run loop body
|
V
Go back to check
let s = String::from("hello"); // s owns the String
|
V
let r = &s; // r borrows s
|
V
println!("{}", r); // OK
println!("{}", s); // OK, s still owns
let s1 = String::from("hello");
|
V
let s2 = s1; // ownership moves to s2
|
V
s1 is no longer valid
|
V
s2 is the new owner
let mut s = String::from("hello");
|
V
change(&mut s);
|
V
fn change(s: &mut String) {
s.push_str(", world");
}
|
V
s is now "hello, world"
Module One: Rust Foundations
|
V
Module Two: Control Flow and Ownership
|
V
Module Three: Custom Types and Error Handling
|
V
Module Four: Collections, Generics, and Traits
|
V
Module Five: Concurrency and Systems Programming
|
V
Module Six: Professional Rust and Capstone
|
V
Certified Rust Programming Expert 🎉
| Loop Type | When to Use | Example |
|---|---|---|
loop | Repeat forever until break | Game loop |
while | Repeat while condition is true | Wait for input |
for | Repeat for each item | Go through a list |
| Feature | Ownership | Borrowing |
|---|---|---|
| Who has the value? | One owner | Owner keeps it |
| Can you change? | Yes, if mutable | Only with &mut |
| Cost | Move transfers ownership | No move, just reference |
| Safety | Prevents double-free | Prevents data races |
| Expression | Statement |
|---|---|
| Produces a value | Performs an action |
5 + 3 | let x = 5; |
if true { 1 } else { 2 } | println!("hi"); |
| Feature | Immutable Borrow | Mutable Borrow |
|---|---|---|
| Syntax | &value | &mut value |
| Can read? | Yes | Yes |
| Can change? | No | Yes |
| How many at once? | Many | Only one |
Lesson 1: if runs code when a condition is true.
Lesson 2: else if and else add more choices.
Lesson 3: Use &&, ||, and ! to combine conditions.
Lesson 4: match compares a value to many patterns.
Lesson 5: loop repeats forever until break.
Lesson 6: while repeats while a condition is true.
Lesson 7: for repeats for each item in a collection.
Lesson 8: Expressions give values; statements do actions.
Lesson 9: if and match can be assigned to variables.
Lesson 10: Ownership: one owner at a time. Moving transfers ownership.
Lesson 11: Borrowing uses & to reference without moving.
Lesson 12: Mutable borrowing uses &mut to change borrowed data.
Lesson 13: Lifetimes track reference validity. Rust often infers them.
Lesson 14: Common mistakes include moved values and missing _ in match.
Lesson 15: Combine decisions, loops, and borrowing in a guessing game.
Congratulations! You have finished Module Two of the Certified Rust Programming Expert course. You learned how to make programs think with if, else, and match. You learned how to repeat actions with loop, while, and for. You also learned Rust’s superpower: ownership and borrowing. These ideas make Rust safe and fast. You learned about lifetimes and how Rust prevents dangling references. You saw many examples from Nigeria and everyday life. You now know common mistakes and best practices. Most importantly, you can write programs that make decisions and repeat tasks, and you understand how Rust manages memory safely. Keep practising, and you will become a Certified Rust Programming Expert!
if and match? if checks one condition. match checks many patterns.loop vs while? Use loop when you want to repeat forever until a break. Use while when you have a condition.&.&mut.break.Match the word to its definition.
| Word | Definition |
|---|---|
1. if | A. Repeats for each item in a collection. |
2. match | B. Runs code when a condition is true. |
3. while | C. Compares a value to many patterns. |
4. for | D. Repeats while a condition is true. |
| 5. Ownership | E. Each value has one owner. |
Answers: 1-B, 2-C, 3-D, 4-A, 5-E
if else.match.loop or while.for.&.Title: “Build a Traffic Light Simulator”
Instructions: In groups of 3–4, write a Rust program that simulates a traffic light. Use match to choose the action for “red”, “yellow”, and “green”. Use a loop to repeat the cycle. Print the light colour and the action. Share your program with the class.
Goal: Practice match, loops, and printing.
Task: Write a Rust program that asks the user for a number. Use if else to print whether the number is positive, negative, or zero. Use a loop to let the user try again until they type “quit”.
Hint: Use parse() to convert input to a number. Use break to exit.
Project: “My School Timetable”
Write a Rust program that stores your school timetable for the week. Use match to print the subject for each day. Use a for loop to go through the days. Add comments to explain each part.
Example output:
Monday: Maths Tuesday: English Wednesday: Science Thursday: History Friday: Sports
Assignment: Create a new Cargo project called number_guess. In main.rs, write a program that:
loop to ask the user to guess.if else if else to say “Too low!”, “Too high!”, or “You win!”.Submit: Your main.rs file and a screenshot of the program running.
if, else if, and else for decisions.match for many patterns.loop, while, and for for repetition.& to reference, &mut to change.match different from if else?loop has no break?for often safer than while?In Module Three, we will dive deeper into Rust. We will learn about:
Result and Option.impl blocks.Debug and Clone.To prepare, make sure you have completed the practical assignment and can write programs with decisions and loops. Review your notes on ownership and borrowing. Bring your curiosity!
See you in Module Three!
End of Module Two – Certified Rust Programming Expert