Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Certified Rust Programming Expert · Lesson 3 of 7

Module Two

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
3
Certified Rust Programming Expert – Module Two

Module Two: Control Flow and Ownership – Making Rust Think and Remember

“Certified Rust Programming Expert” – A complete path from beginner to professional

Module Introduction

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!

Learning Objectives

After finishing this module, you will be able to:

  • Use if, else if, and else to make decisions in Rust.
  • Use match to compare a value against many patterns.
  • Use loop, while, and for to repeat actions.
  • Understand the difference between expressions and statements.
  • Explain the basics of ownership and borrowing in simple words.
  • Use borrowing with & and mutable borrowing with &mut.
  • Recognize common mistakes with control flow and ownership.
  • Complete a mini project and practical assignment.

Warm-up Story: Chidi the Robot Learns to Decide

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.

Main Lessons

Lesson 1: Making Decisions with if

Definition: 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:

  • Write if followed by a condition.
  • The condition must be a bool (true or false).
  • Open a block with { and close with }.
  • Put the code to run inside the block.

Mini summary: if runs code only when a condition is true. It is the first step to making your program smart.

Lesson 2: Adding else and else if

Definition: 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.

Lesson 3: Conditions and Boolean Logic

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.

Lesson 4: The match Expression – A Better Way to Choose

Definition: 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:

  • Write match followed by the value.
  • Inside { }, write patterns with => and code.
  • Separate each arm with a comma.
  • Use _ 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.

Lesson 5: Repeating with loop

Definition: 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!

Lesson 6: while Loops – Repeat While True

Definition: 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.

Lesson 7: for Loops – Repeat a Known Number of Times

Definition: 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.

Lesson 8: Expressions vs Statements

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.

Lesson 9: Using if in a let – Expressions in Action

Definition: 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.

Lesson 10: Introduction to Ownership – Rust’s Superpower

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:

  • Each value has one owner.
  • When you assign to another variable, ownership moves.
  • The original variable cannot be used after the move.
  • When the owner goes out of scope, the value is freed.

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.

Lesson 11: Borrowing – Using Without Taking

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:

  • Use & before a variable to borrow it.
  • The function takes &Type as a parameter.
  • The owner keeps ownership.
  • The borrower can read the value but not change it (unless mutable).

Mini summary: Borrowing uses & to reference a value without moving it. The owner keeps ownership. This is safe and efficient.

Lesson 12: Mutable Borrowing – Changing Borrowed Data

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:

  • Make the variable mutable with let mut.
  • Pass &mut variable to the function.
  • The function takes &mut Type.
  • Only one mutable borrow at a time is allowed.

Mini summary: Use &mut to borrow and change. You can only have one mutable borrow at a time. This prevents data races.

Lesson 13: Lifetimes – A Simple Introduction

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:

  • Use 'a to name a lifetime.
  • Add it to references: &'a str.
  • Rust checks that references live long enough.
  • Most of the time, you don’t need to write lifetimes. Rust figures it out.

Mini summary: Lifetimes track how long references are valid. They prevent dangling references. Rust often infers them automatically.

Lesson 14: Common Mistakes with Control Flow and Ownership

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:

MistakeWhat happensRust’s help
Using a moved valueValue no longer validCompiler error: “value borrowed after move”
Multiple mutable borrowsData race possibleCompiler error: “cannot borrow as mutable more than once”
Missing _ in matchNot all cases coveredCompiler error: “non-exhaustive patterns”
Infinite loop without breakProgram never stopsYou must add a break condition
Using == with different typesType mismatchCompiler error
Forgetting mut for mutable borrowCannot borrow as mutableCompiler error

Mini summary: Rust catches many mistakes early. Read the error messages. They tell you exactly what to fix.

Lesson 15: Putting It All Together – A Small Program

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!

Key Vocabulary

WordSimple Definition
Control flowThe order in which code runs. Decisions and loops change it.
ifRuns code when a condition is true.
elseRuns code when the if condition is false.
else ifChecks another condition if the first is false.
matchCompares a value to many patterns.
loopRepeats forever until break.
whileRepeats while a condition is true.
forRepeats for each item in a collection.
ExpressionProduces a value.
StatementPerforms an action, no value.
OwnershipEach value has one owner. When owner goes away, value is dropped.
BorrowingUsing a value without taking ownership (&).
Mutable borrowBorrowing to change (&mut).
MoveTransferring ownership from one variable to another.
LifetimeHow long a reference is valid.
ScopeThe part of code where a variable is valid.

Important Concepts

  • Conditions: if and else use bool values.
  • Pattern matching: match is powerful and safe.
  • Loops: loop, while, and for repeat actions.
  • Expressions: Rust is expression-based. if and match can give values.
  • Ownership: One owner at a time. Prevents memory bugs.
  • Borrowing: Use & to reference without moving. Use &mut to change.
  • Lifetimes: Track reference validity. Often inferred automatically.
  • Compiler as guard: Rust checks ownership and borrowing rules at compile time.

Step-by-step Explanations

How to use match step by step

  1. Identify the value you want to check.
  2. Write match value {.
  3. List each possible pattern with => and the code to run.
  4. Separate arms with commas.
  5. Add a catch-all _ if needed.
  6. Close with }.

Example:

  let day = "Monday";
  match day {
      "Monday" => println!("Start of week"),
      "Friday" => println!("Almost weekend"),
      _ => println!("Just another day"),
  }
  

How to borrow step by step

  1. Create a variable that owns a value.
  2. Write a function that takes a reference: fn my_func(s: &String).
  3. Call the function with &my_variable.
  4. Inside the function, use the reference without taking ownership.
  5. The owner keeps ownership and can use the value after.

Example:

  fn main() {
      let s = String::from("hello");
      print_length(&s);
      println!("Still own: {}", s);
  }
  fn print_length(s: &String) {
      println!("Length: {}", s.len());
  }
  

How to use a mutable borrow step by step

  1. Make the variable mutable: let mut s = String::from("hello");.
  2. Write a function that takes &mut String.
  3. Call the function with &mut s.
  4. The function can change the value.
  5. After the borrow ends, the owner can use the value again.

Real-life Examples

  • Traffic lights: Use match to decide stop, ready, or go.
  • Bank ATMs: Use if to check if PIN is correct.
  • Game loops: Use loop to keep the game running until you quit.
  • Music players: Use for to play each song in a playlist.
  • Online forms: Use while to keep asking until valid input.

Nigerian Examples

  • POS machine: Uses if to check if card is valid.
  • Traffic in Lagos: Uses match to decide when to stop and go.
  • Market trading: Uses while to keep selling while there is stock.
  • Nollywood streaming: Uses for to play each episode.
  • Generator: Uses loop to keep running until fuel finishes.

Fun Examples Children Can Relate To

  • Video games: if checks if you won or lost.
  • Robot: while keeps the robot moving while battery is full.
  • Chat apps: loop keeps the app running until you close it.
  • Music: for plays each song in your playlist.
  • School quiz: match checks your answer against the correct one.

Everyday Examples

  • Alarm clock: while time is not up, keep ringing.
  • Microwave: for each second, count down.
  • Traffic light: match colour to action.
  • ATM: if PIN is correct, allow withdrawal.
  • Phone keyboard: for each tap, show letter.

Parent Tips

  • Encourage your child to explain their code out loud. It helps them learn.
  • Let them make mistakes. Errors are learning opportunities.
  • Use everyday examples (traffic lights, cooking) to explain control flow.
  • Set a small daily coding time. Consistency helps.
  • Celebrate small wins, like making a working loop.
  • Be patient. Ownership takes time to understand.
  • Ask them to teach you what they learned. Teaching is the best way to learn.
  • Keep it fun. Use games and stories.
  • Remind them that even expert programmers make mistakes.
  • Encourage them to read error messages carefully.

Interesting Facts

  • Rust’s ownership system was inspired by research from the 1990s.
  • Rust prevents data races at compile time. No other language does this as well.
  • The match keyword is one of Rust’s most loved features.
  • Rust’s for loop is safer than C’s for loop.
  • Rust’s compiler is often called “the best teacher” because of its clear error messages.
  • Many companies rewrite their software in Rust to stop crashes.
  • Lifetimes are checked at compile time, so there is no runtime cost.
  • Borrowing is one of Rust’s most unique features.

Did You Know?

  • Did you know that Rust can prevent entire classes of bugs before your program runs?
  • Did you know that the Linux kernel now uses Rust for some drivers?
  • Did you know that Rust’s match must cover every possible case?
  • Did you know that loop can return a value with break?
  • Did you know that borrowing is checked at compile time, so there is no runtime cost?
  • Did you know that you can have many immutable borrows at the same time?
  • Did you know that you can only have one mutable borrow at a time?
  • Did you know that lifetimes help Rust prevent dangling references?

Remember This

  • 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.
  • Expressions give values; statements do actions.
  • Ownership: one owner at a time.
  • Borrowing: use & to reference, &mut to change.
  • Lifetimes track reference validity.
  • Rust’s compiler catches many mistakes before running.

Common Mistakes

  • Forgetting to add break in a loop.
  • Using a moved value after moving it.
  • Trying to have two mutable borrows at the same time.
  • Forgetting the catch-all _ in match.
  • Using = instead of == in conditions.
  • Forgetting that if conditions must be bool.
  • Not trimming input before parsing.
  • Ignoring compiler error messages.

Best Practices

  • Prefer for loops over while when possible.
  • Use match instead of long if else chains.
  • Borrow instead of moving when you don’t need ownership.
  • Keep functions small and focused.
  • Use meaningful names.
  • Write comments for tricky parts.
  • Run cargo check often.
  • Read compiler messages carefully.
  • Format your code with cargo fmt.
  • Test your code with cargo test.

Illustrations and Diagrams

Control Flow Decision Tree

  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
  

Loop Flowchart

  Start
    |
    V
  Check condition (while) or enter loop
    |
    +--> Condition false? --> Exit loop
    |
    +--> Condition true? --> Run loop body
              |
              V
         Go back to check
  

Ownership and Borrowing

  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
  

Move Semantics

  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
  

Mutable Borrow Flow

  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"
  

Your Learning Journey

  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 🎉
  

Comparison Tables

Loop Comparison

Loop TypeWhen to UseExample
loopRepeat forever until breakGame loop
whileRepeat while condition is trueWait for input
forRepeat for each itemGo through a list

Ownership vs Borrowing

FeatureOwnershipBorrowing
Who has the value?One ownerOwner keeps it
Can you change?Yes, if mutableOnly with &mut
CostMove transfers ownershipNo move, just reference
SafetyPrevents double-freePrevents data races

Expression vs Statement

ExpressionStatement
Produces a valuePerforms an action
5 + 3let x = 5;
if true { 1 } else { 2 }println!("hi");

Immutable vs Mutable Borrow

FeatureImmutable BorrowMutable Borrow
Syntax&value&mut value
Can read?YesYes
Can change?NoYes
How many at once?ManyOnly one

Lesson Summaries

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.

End-of-Module Summary

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!

Frequently Asked Questions

  1. What is control flow? The order in which code runs. Decisions and loops change it.
  2. What is the difference between if and match? if checks one condition. match checks many patterns.
  3. When should I use loop vs while? Use loop when you want to repeat forever until a break. Use while when you have a condition.
  4. What is ownership? Rust’s system where each value has one owner. When the owner goes away, the value is dropped.
  5. What is borrowing? Using a value without taking ownership. You use &.
  6. What is a mutable borrow? Borrowing to change the value. You use &mut.
  7. Why can’t I have two mutable borrows? It could cause data races. Rust prevents this at compile time.
  8. What is an expression? Code that produces a value.
  9. What is a statement? Code that performs an action but produces no value.
  10. How do I stop an infinite loop? Use break.

Matching Exercises

Match the word to its definition.

WordDefinition
1. ifA. Repeats for each item in a collection.
2. matchB. Runs code when a condition is true.
3. whileC. Compares a value to many patterns.
4. forD. Repeats while a condition is true.
5. OwnershipE. Each value has one owner.

Answers: 1-B, 2-C, 3-D, 4-A, 5-E

Scenario-based Exercises

  1. Scenario: You want to check if a student passed or failed. Which control flow do you use?
    Answer: if else.
  2. Scenario: You want to check the day of the week and print a message for each day. Which control flow is best?
    Answer: match.
  3. Scenario: You want to keep asking for a password until it is correct. Which loop?
    Answer: loop or while.
  4. Scenario: You have a list of names and want to greet each one. Which loop?
    Answer: for.
  5. Scenario: You want to use a String in a function but keep ownership. What do you use?
    Answer: Borrow with &.

Group Activity

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.

Individual Activity

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.

Mini Project

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
  

Practical Assignment

Assignment: Create a new Cargo project called number_guess. In main.rs, write a program that:

  1. Stores a secret number (e.g., 7).
  2. Uses a loop to ask the user to guess.
  3. Reads the guess and converts it to a number.
  4. Uses if else if else to say “Too low!”, “Too high!”, or “You win!”.
  5. Breaks the loop when the guess is correct.
  6. Prints the number of attempts.
  7. Uses a function to check the guess and return a message.

Submit: Your main.rs file and a screenshot of the program running.

Key Takeaways

  • Use if, else if, and else for decisions.
  • Use match for many patterns.
  • Use loop, while, and for for repetition.
  • Expressions give values; statements do actions.
  • Ownership: one owner at a time.
  • Borrowing: use & to reference, &mut to change.
  • Lifetimes track reference validity.
  • Rust’s compiler catches many mistakes early.
  • Practice and read error messages carefully.
  • You are on your way to becoming a Certified Rust Expert.

Classroom Discussion Questions

  1. Why do programs need to make decisions?
  2. How is match different from if else?
  3. What happens if a loop has no break?
  4. Why is for often safer than while?
  5. What is the difference between an expression and a statement?
  6. Why does Rust have ownership?
  7. How does borrowing help us use data without moving it?
  8. Why can’t we have two mutable borrows at the same time?
  9. What did Chidi the robot learn in the warm-up story?
  10. Where do you see control flow in Nigeria?

Preparation for Module Three

In Module Three, we will dive deeper into Rust. We will learn about:

  • Structs and enums (building your own data types).
  • Pattern matching with enums.
  • Error handling with Result and Option.
  • Methods and impl blocks.
  • Deriving traits like Debug and Clone.
  • Writing bigger programs.

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

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→