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

Module Four

📖 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.
5
Certified Rust Programming Expert – Module Four

Module Four: Collections, Generics, and Traits – Storing Many Things and Writing Flexible Code

“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 store single values in variables. In Module Two, you learned how to make decisions and repeat actions. In Module Three, you learned how to build your own data types with structs and enums.

But what if you need to store many values at once? Imagine a school with 500 students. You cannot create 500 separate variables. That would be crazy! Rust gives you collections to store many values in one place.

In this module, we will learn about vectors (lists of values), strings (text), and hash maps (key-value storage). We will also learn about iterators and closures to work with collections. Then we will explore generics and traits to write flexible code. Finally, we will learn about modules, testing, and debugging to build bigger, safer programs.

By the end, you will be able to store and manage many values, write reusable code, and build complete projects. Let’s begin!

Learning Objectives

After finishing this module, you will be able to:

  • Use vectors to store lists of values.
  • Use strings to store and manipulate text.
  • Use hash maps to store key-value pairs.
  • Use iterators to go through collections.
  • Use closures to write short, inline functions.
  • Write generic functions and structs.
  • Define and implement traits.
  • Organise code with modules.
  • Write and run tests.
  • Debug programs effectively.
  • Complete a mini project and practical assignment.

Warm-up Story: Ada’s Big Market List

Ada is going to the market in Lagos. Her mother gives her a long list of things to buy: rice, beans, tomatoes, peppers, onions, oil, salt, and maggi. Ada writes the list on a piece of paper.

At the market, Ada needs to check each item. She also needs to remember the price of each item. And she needs to know how much money she has spent. If she uses separate papers for each item, she will get confused. Instead, she uses one notebook with columns for item, price, and quantity.

In Rust, that notebook is like a vector (a list of items) and a hash map (item to price). Ada can add items, remove items, and look up prices quickly. Just like Ada’s notebook, Rust collections help you store and manage many things without confusion.

But Ada also wants to write a small helper that can calculate the total price of any basket of goods, whether it is rice and beans or tomatoes and peppers. She does not want to write a new helper for every possible combination. She uses a generic function that works with any list of items. She also uses a trait to make sure each item has a price.

Finally, Ada wants to keep her notebook safe. She writes a small note to herself: “Always check the price before buying.” That note is like a test. And when something goes wrong, she checks her notebook carefully. That is debugging.

Moral of the story: Collections help you store many values. Generics and traits help you write flexible code. Tests and debugging help you keep your programs safe.

Main Lessons

Lesson 1: Vectors – Lists of Values

Definition: A vector is a list that can grow or shrink. It stores many values of the same type.

Why it is important: You often need to store many items, like names, scores, or prices.

Simple explanation: Think of a shopping list. You can add items, remove items, and read them one by one. A vector is like that list.

Real-life example: A playlist of songs. You can add songs, remove songs, and play them in order.

School example: A list of students in a class.

Home example: A list of chores to do.

Nigerian example: A list of goods in a market stall.

Illustration:

  let mut scores = vec![85, 90, 78, 92];

  scores.push(88);        // add a score
  scores.remove(0);       // remove first score

  for score in &scores {
      println!("Score: {}", score);
  }
  

Step-by-step:

  • Create with vec![] or Vec::new().
  • Use push to add items.
  • Use remove to delete items.
  • Use for to go through items.
  • Use & to borrow the vector without moving it.

Mini summary: Vectors store lists of values. They can grow and shrink. Use vec! to create them.

Lesson 2: Strings – Working with Text

Definition: A String is a growable, mutable text type. It stores words, sentences, and paragraphs.

Why it is important: Programs need to handle names, messages, and user input.

Simple explanation: A String is like a notebook where you can write, erase, and add more words.

Real-life example: A text message you type on your phone.

School example: Your name written on your exercise book.

Home example: A shopping list written on paper.

Nigerian example: A broadcast message sent to customers: “Buy 1 get 1 free!”

Illustration:

  let mut greeting = String::from("Hello");
  greeting.push_str(", world!");
  greeting.push('!');

  println!("{}", greeting);       // Hello, world!!
  println!("Length: {}", greeting.len());
  

Step-by-step:

  • Create with String::from("text") or "text".to_string().
  • Use push_str to add a string slice.
  • Use push to add a single character.
  • Use len() to get the length.
  • Use & to borrow as a string slice (&str).

Mini summary: Strings store text. They can grow and change. Use String::from to create them.

Lesson 3: Hash Maps – Key-Value Storage

Definition: A hash map stores pairs of keys and values. You use the key to find the value.

Why it is important: You often need to look up information quickly by a name or ID.

Simple explanation: Think of a phone book. You look up a name (key) to find a phone number (value).

Real-life example: A dictionary. You look up a word to find its meaning.

School example: A class register. You look up a student’s name to find their score.

Home example: A recipe book. You look up a dish to find ingredients.

Nigerian example: A market price list. You look up “rice” to find the price.

Illustration:

  use std::collections::HashMap;

  let mut prices = HashMap::new();
  prices.insert("rice", 500);
  prices.insert("beans", 300);

  match prices.get("rice") {
      Some(price) => println!("Rice costs {}", price),
      None => println!("Rice not found"),
  }
  

Step-by-step:

  • Import with use std::collections::HashMap;.
  • Create with HashMap::new().
  • Use insert(key, value) to add pairs.
  • Use get(key) to find a value. It returns Option.
  • Use for (key, value) in &map to go through all pairs.

Mini summary: Hash maps store key-value pairs. Use them for fast lookups. get returns Option.

Lesson 4: Iterators – Going Through Collections

Definition: An iterator is an object that goes through items in a collection, one at a time.

Why it is important: Iterators make it easy to process lists without writing manual loops.

Simple explanation: Think of a bus conductor. He goes to each passenger, one by one, to collect fares. An iterator does the same with items.

Real-life example: A teacher marking attendance, calling each student’s name.

School example: Going through each question in an exam.

Home example: Checking each item on a shopping list.

Nigerian example: A trader counting each item in a basket.

Illustration:

  let numbers = vec![1, 2, 3, 4, 5];

  let doubled: Vec = numbers.iter().map(|x| x * 2).collect();
  println!("{:?}", doubled); // [2, 4, 6, 8, 10]

  let evens: Vec<&i32> = numbers.iter().filter(|x| *x % 2 == 0).collect();
  println!("{:?}", evens); // [2, 4]
  

Step-by-step:

  • Call .iter() to get an iterator.
  • Use .map() to transform each item.
  • Use .filter() to keep only some items.
  • Use .collect() to turn the result back into a collection.

Mini summary: Iterators go through items one by one. Use map and filter to process them.

Lesson 5: Closures – Short Inline Functions

Definition: A closure is a small function you can write inline. It can capture values from around it.

Why it is important: Closures make code short and easy to read, especially with iterators.

Simple explanation: Think of a quick note you write on a sticky paper. It does one small job.

Real-life example: A recipe note: “Add salt to taste.”

School example: A short reminder: “Bring calculator.”

Home example: A sticky note: “Buy milk.”

Nigerian example: A short instruction: “Add pepper small.”

Illustration:

  let add = |a, b| a + b;
  println!("{}", add(3, 4)); // 7

  let numbers = vec![1, 2, 3];
  let doubled: Vec = numbers.iter().map(|x| x * 2).collect();
  println!("{:?}", doubled); // [2, 4, 6]
  

Step-by-step:

  • Write |parameters| expression.
  • Use { } for multiple lines.
  • Closures can capture variables from outside.
  • Use them with map, filter, and other iterator methods.

Mini summary: Closures are short functions. They are perfect for iterators. Use |x| to write them.

Lesson 6: Generics – Writing Flexible Code

Definition: Generics let you write code that works with many types, without repeating yourself.

Why it is important: You can write one function that works for numbers, text, and more.

Simple explanation: Think of a water bottle. It can hold water, juice, or milk. The bottle is generic. The contents can be different types.

Real-life example: A delivery box. It can carry books, clothes, or food.

School example: A school bag. It can carry maths books, English books, or science books.

Home example: A plate. You can put rice, beans, or salad on it.

Nigerian example: A market basket. It can carry yams, tomatoes, or peppers.

Illustration:

  fn largest(list: &[T]) -> &T {
      let mut largest = &list[0];
      for item in list {
          if item > largest {
              largest = item;
          }
      }
      largest
  }

  let numbers = vec![34, 50, 25, 100, 65];
  println!("Largest: {}", largest(&numbers));

  let chars = vec!['y', 'm', 'a', 'q'];
  println!("Largest: {}", largest(&chars));
  

Step-by-step:

  • Write <T> after the function name.
  • Use T as a type in parameters and return.
  • Add trait bounds like T: PartialOrd if needed.
  • Call the function with any type that meets the bounds.

Mini summary: Generics let you write code for many types. Use <T> to define them. Add traits to set rules.

Lesson 7: Traits – Shared Behaviour

Definition: A trait defines behaviour that types can share. It is like a contract.

Why it is important: Traits let you write code that works with many types, as long as they have the required behaviour.

Simple explanation: Think of a driving licence. Any person with a licence can drive. The licence is a trait. Different people (types) can have it.

Real-life example: A “can swim” trait. Fish, humans, and boats can all swim.

School example: A “can read” trait. Students, teachers, and librarians can all read.

Home example: A “can cook” trait. Mum, dad, and auntie can all cook.

Nigerian example: A “can trade” trait. Market men, market women, and online sellers can all trade.

Illustration:

  trait Greet {
      fn greet(&self) -> String;
  }

  struct Person {
      name: String,
  }

  impl Greet for Person {
      fn greet(&self) -> String {
          format!("Hello, my name is {}", self.name)
      }
  }

  let p = Person { name: String::from("Ada") };
  println!("{}", p.greet());
  

Step-by-step:

  • Define with trait Name { }.
  • List method signatures inside.
  • Implement with impl Trait for Type { }.
  • Call the methods on instances.

Mini summary: Traits define shared behaviour. Types implement traits. Use them to write flexible code.

Lesson 8: Modules – Organising Your Code

Definition: A module is a way to group related code together. It keeps your project tidy.

Why it is important: As programs grow, you need to organise them. Modules prevent confusion.

Simple explanation: Think of a school. It has different classrooms for different subjects. Each classroom is a module.

Real-life example: A hospital has different departments: emergency, pharmacy, laboratory.

School example: Different subjects in different exercise books.

Home example: Different drawers for clothes, utensils, and tools.

Nigerian example: A market has different sections: food, clothes, electronics.

Illustration:

  mod greetings {
      pub fn hello() {
          println!("Hello from the greetings module!");
      }

      pub mod farewells {
          pub fn bye() {
              println!("Goodbye from the farewells module!");
          }
      }
  }

  fn main() {
      greetings::hello();
      greetings::farewells::bye();
  }
  

Step-by-step:

  • Write mod name { } to create a module.
  • Use pub to make items public.
  • Access with module::item.
  • Nest modules for deeper organisation.

Mini summary: Modules group related code. Use mod and pub. They keep projects tidy.

Lesson 9: Testing – Checking Your Work

Definition: A test is code that checks if your program works correctly.

Why it is important: Tests catch mistakes early. They give you confidence.

Simple explanation: Like checking your homework before submitting. Tests check your code before running it for real.

Real-life example: A doctor checks your temperature before giving medicine.

School example: A teacher marks your test and gives feedback.

Home example: Tasting food before serving guests.

Nigerian example: Checking the generator fuel before starting it.

Illustration:

  fn add(a: i32, b: i32) -> i32 {
      a + b
  }

  #[cfg(test)]
  mod tests {
      use super::*;

      #[test]
      fn test_add() {
          assert_eq!(add(2, 3), 5);
          assert_eq!(add(-1, 1), 0);
      }
  }
  

Step-by-step:

  • Add #[cfg(test)] to a module.
  • Write test functions with #[test].
  • Use assert_eq! to check values.
  • Run with cargo test.

Mini summary: Tests check your code. Use #[test] and assert_eq!. Run with cargo test.

Lesson 10: Debugging – Finding and Fixing Mistakes

Definition: Debugging is the process of finding and fixing mistakes (bugs) in your code.

Why it is important: All programmers make mistakes. Debugging helps you fix them.

Simple explanation: Like finding a typo in your homework and correcting it.

Real-life example: A mechanic checking a car engine to find a problem.

School example: Checking your maths work to find an error.

Home example: Finding why the TV remote is not working.

Nigerian example: A trader checking why the POS is not printing receipts.

Illustration:

  Debugging steps:
  1. Read the error message.
  2. Find the line of code.
  3. Check the logic.
  4. Fix the mistake.
  5. Run again.

  Use println! to print values.
  Use dbg! to print with file and line.
  Use cargo check to catch errors early.
  

Step-by-step:

  • Read compiler error messages carefully.
  • Use println! to print variables.
  • Use dbg! to print with file and line info.
  • Simplify the code to isolate the problem.
  • Ask for help if stuck.

Mini summary: Debugging finds and fixes mistakes. Read error messages. Use println! and dbg!. Be patient.

Lesson 11: 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 12: Smart Pointers – Box, Rc, and RefCell

Definition: Smart pointers are types that act like pointers but have extra abilities. Rust has Box, Rc, and RefCell.

Why it is important: They help you manage memory in advanced situations.

Simple explanation: A normal pointer is like a finger pointing at something. A smart pointer is a finger with a brain. It can do extra things.

Real-life example: A TV remote is a smart pointer. It points to the TV but also controls it.

School example: A class monitor is a smart pointer. They represent the class but also do tasks.

Home example: A universal remote controls many devices.

Nigerian example: A POS machine is a smart pointer. It handles payment and printing.

Illustration:

  // Box: stores data on the heap
  let b = Box::new(5);
  println!("b = {}", b);

  // Rc: reference counted, shared ownership
  use std::rc::Rc;
  let a = Rc::new(String::from("hello"));
  let b = Rc::clone(&a);
  println!("Count: {}", Rc::strong_count(&a)); // 2
  

Mini summary: Smart pointers add abilities. Box stores on heap. Rc allows shared ownership. RefCell allows inner mutability.

Lesson 13: Common Mistakes with Collections and Generics

Definition: Mistakes happen. Knowing them helps you avoid them.

Why it is important: Rust’s compiler catches many mistakes. Learn from the messages.

Simple explanation: Like forgetting to add an item to your market list. Rust reminds you.

Real-life example: Forgetting to save a file before closing.

School example: Forgetting to write your name on an exam.

Home example: Forgetting to lock the door.

Nigerian example: Forgetting to collect your change in a taxi.

Table of common mistakes:

MistakeWhat happensRust’s help
Using vector after movingCompiler error“value borrowed after move”
Getting from hash map without checkingPanic if missingget returns Option
Missing trait bound in genericCompiler error“trait not implemented”
Forgetting pub in moduleCannot access“private module”
Test not marked with #[test]Test not runNo output
Forgetting & in iteratorMoves collectionCompiler error

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

Lesson 14: Best Practices for Collections, Generics, and Modules

Definition: Best practices are good habits that make your code clean and safe.

Why it is important: Good habits make coding easier and more fun.

Simple explanation: Like keeping your room tidy, best practices keep your code tidy.

Real-life example: A chef keeps the kitchen clean. A programmer keeps code clean.

School example: Writing neatly in your notebook. Best practices make code readable.

Home example: Washing plates after eating. Best practices prevent problems later.

Nigerian example: Keeping your market stall organised. Best practices keep code organised.

List of best practices:

  • Use vectors for lists, hash maps for lookups.
  • Use & to borrow collections instead of moving them.
  • Use iterators and closures for clean code.
  • Use generics to avoid repeating code.
  • Use traits to define shared behaviour.
  • Organise code with modules.
  • Write tests for important functions.
  • Use dbg! for debugging.
  • Keep functions small and focused.
  • Write comments to explain why.

Mini summary: Good habits make you a better programmer. Start them now.

Lesson 15: Putting It All Together – A Small Program

Let’s write a program that uses collections, iterators, closures, and modules.

Program: Market Price Checker

  use std::collections::HashMap;

  mod market {
      use std::collections::HashMap;

      pub fn create_prices() -> HashMap {
          let mut prices = HashMap::new();
          prices.insert(String::from("rice"), 500.0);
          prices.insert(String::from("beans"), 300.0);
          prices.insert(String::from("tomatoes"), 150.0);
          prices
      }

      pub fn total_cost(prices: &HashMap, items: &[&str]) -> f64 {
          items.iter()
              .filter_map(|item| prices.get(*item))
              .sum()
      }
  }

  fn main() {
      let prices = market::create_prices();
      let basket = vec!["rice", "beans", "tomatoes"];

      let total = market::total_cost(&prices, &basket);
      println!("Total cost: ₦{}", total);

      for (item, price) in &prices {
          println!("{}: ₦{}", item, price);
      }
  }
  

Explanation:

  • market is a module that groups related functions.
  • create_prices returns a hash map of items and prices.
  • total_cost uses an iterator, filter, and sum to calculate total.
  • main calls the functions and prints the result.

Mini summary: This program combines modules, hash maps, vectors, iterators, and closures. It is a complete example of what you can build.

Key Vocabulary

WordSimple Definition
VectorA growable list of values.
StringA growable text type.
Hash MapA collection of key-value pairs.
IteratorAn object that goes through items one by one.
ClosureA short inline function.
GenericCode that works with many types.
TraitShared behaviour that types can implement.
ModuleA group of related code.
TestCode that checks if your program works.
DebuggingFinding and fixing mistakes.
LifetimeHow long a reference is valid.
Smart PointerA pointer with extra abilities.
BoxStores data on the heap.
RcReference counted, shared ownership.
RefCellAllows inner mutability.

Important Concepts

  • Vectors: Store lists of values. Use vec!.
  • Strings: Store text. Use String::from.
  • Hash Maps: Store key-value pairs. Use HashMap::new.
  • Iterators: Go through items. Use map, filter, collect.
  • Closures: Short functions. Use |x|.
  • Generics: Write code for many types. Use <T>.
  • Traits: Define shared behaviour. Use trait and impl.
  • Modules: Organise code. Use mod and pub.
  • Testing: Check your code. Use #[test].
  • Debugging: Find and fix mistakes. Use dbg!.
  • Lifetimes: Track reference validity.
  • Smart Pointers: Box, Rc, RefCell for advanced memory management.

Step-by-step Explanations

How to use a vector step by step

  1. Create with let mut v = vec![1, 2, 3];.
  2. Add with v.push(4);.
  3. Remove with v.remove(0);.
  4. Access with v[0] or v.get(0).
  5. Loop with for item in &v { }.

Example:

  let mut scores = vec![85, 90, 78];
  scores.push(92);
  for score in &scores {
      println!("Score: {}", score);
  }
  

How to use a hash map step by step

  1. Import with use std::collections::HashMap;.
  2. Create with let mut map = HashMap::new();.
  3. Insert with map.insert("key", value);.
  4. Get with map.get("key"); returns Option.
  5. Loop with for (k, v) in &map { }.

Example:

  use std::collections::HashMap;

  let mut prices = HashMap::new();
  prices.insert("rice", 500);
  prices.insert("beans", 300);

  for (item, price) in &prices {
      println!("{}: {}", item, price);
  }
  

How to write a test step by step

  1. Add #[cfg(test)] before a module.
  2. Write mod tests { }.
  3. Add use super::*; to access functions.
  4. Write #[test] before each test function.
  5. Use assert_eq! to check values.
  6. Run with cargo test.

Example:

  fn add(a: i32, b: i32) -> i32 {
      a + b
  }

  #[cfg(test)]
  mod tests {
      use super::*;

      #[test]
      fn test_add() {
          assert_eq!(add(2, 3), 5);
      }
  }
  

How to define a trait step by step

  1. Write trait Name { }.
  2. Add method signatures inside.
  3. Write impl Name for Type { }.
  4. Implement the methods.
  5. Call them on instances.

Example:

  trait Greet {
      fn greet(&self) -> String;
  }

  struct Person { name: String }

  impl Greet for Person {
      fn greet(&self) -> String {
          format!("Hello, {}", self.name)
      }
  }
  

Real-life Examples

  • Playlists: Vectors store songs.
  • Phone books: Hash maps store names and numbers.
  • Chat apps: Strings store messages.
  • Online stores: Hash maps store product prices.
  • School records: Vectors store student names.

Nigerian Examples

  • Market list: Vector of items to buy.
  • Price list: Hash map of item to price.
  • POS transactions: Vector of transactions.
  • Bank accounts: Hash map of account number to balance.
  • Customer messages: String of text.

Fun Examples Children Can Relate To

  • Video game inventory: Vector of items.
  • High scores: Vector of numbers.
  • Pet names: Vector of strings.
  • Superpowers: Enum with Flying, Strength, Invisibility.
  • Treasure map: Hash map of location to treasure.

Everyday Examples

  • Shopping list: Vector of items.
  • Contact list: Hash map of name to phone.
  • To-do list: Vector of tasks.
  • Recipe: Vector of steps.
  • Weather forecast: Hash map of day to weather.

Parent Tips

  • Encourage your child to explain their collections out loud.
  • Let them make mistakes. Errors are learning opportunities.
  • Use everyday examples (shopping list, contact list) to explain collections.
  • Set a small daily coding time. Consistency helps.
  • Celebrate small wins, like creating a working vector.
  • Be patient. Generics and traits take 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 Vec is similar to Python’s list and Java’s ArrayList.
  • Rust’s HashMap uses a fast hashing algorithm.
  • Iterators in Rust are lazy: they only do work when needed.
  • Closures can capture variables by reference, by mutable reference, or by value.
  • Generics in Rust have zero runtime cost.
  • Traits are similar to interfaces in other languages.
  • Rust’s module system is inspired by ML and Haskell.
  • cargo test runs all tests in your project.
  • dbg! prints the file name and line number.
  • Lifetimes are checked at compile time, so there is no runtime cost.

Did You Know?

  • Did you know that Rust’s Vec can grow automatically?
  • Did you know that HashMap does not keep items in order?
  • Did you know that iter() borrows items, while into_iter() takes ownership?
  • Did you know that closures can be stored in variables?
  • Did you know that generics can be used with structs and enums too?
  • Did you know that traits can have default methods?
  • Did you know that modules can be nested inside other modules?
  • Did you know that tests can be run in parallel?
  • Did you know that dbg! returns the value, so you can use it inline?
  • Did you know that Box is often used for recursive types?

Remember This

  • Vectors store lists of values.
  • Strings store text.
  • Hash maps store key-value pairs.
  • Iterators go through items one by one.
  • Closures are short functions.
  • Generics let you write code for many types.
  • Traits define shared behaviour.
  • Modules organise code.
  • Tests check your code.
  • Debugging finds and fixes mistakes.
  • Lifetimes track reference validity.
  • Smart pointers add abilities.

Common Mistakes

  • Forgetting to import HashMap.
  • Using get without handling None.
  • Forgetting & when iterating over a vector.
  • Using unwrap on a hash map lookup.
  • Forgetting trait bounds in generics.
  • Forgetting pub in modules.
  • Forgetting #[test] before test functions.
  • Ignoring compiler error messages.

Best Practices

  • Use vectors for lists, hash maps for lookups.
  • Use & to borrow collections.
  • Use iterators and closures for clean code.
  • Use generics to avoid repeating code.
  • Use traits to define shared behaviour.
  • Organise code with modules.
  • Write tests for important functions.
  • Use dbg! for debugging.
  • Keep functions small and focused.
  • Write comments to explain why.

Illustrations and Diagrams

Vector Operations

  let mut v = vec![1, 2, 3];
        |
        V
  v.push(4);        // [1, 2, 3, 4]
        |
        V
  v.remove(0);      // [2, 3, 4]
        |
        V
  for x in &v { }   // go through items
  

Hash Map Lookup

  HashMap
  +--------+--------+
  |  Key   | Value  |
  +--------+--------+
  | "rice" |  500   |
  | "beans"|  300   |
  +--------+--------+
        |
        V
  map.get("rice") --> Some(500)
  map.get("yam")  --> None
  

Iterator Pipeline

  Vector: [1, 2, 3, 4, 5]
        |
        V
  .iter()        --> 1, 2, 3, 4, 5
        |
        V
  .map(|x| x*2)  --> 2, 4, 6, 8, 10
        |
        V
  .filter(|x| x>5) --> 6, 8, 10
        |
        V
  .collect()     --> Vec [6, 8, 10]
  

Module Structure

  project/
  ├── src/
  │   ├── main.rs
  │   ├── market.rs      <-- module
  │   └── utils.rs       <-- module
  └── Cargo.toml
  

Test Flow

  Write code
      |
      V
  Write tests with #[test]
      |
      V
  Run cargo test
      |
      V
  Tests pass? --Yes--> Done
      |
      No
      |
      V
  Fix code and run again
  

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

Collection Comparison

CollectionUse CaseExample
VectorOrdered list of itemsShopping list
StringTextMessage
Hash MapKey-value lookupPhone book

Generic vs Trait

FeatureGenericTrait
PurposeWork with many typesDefine shared behaviour
Syntax<T>trait Name { }
Examplefn largest<T>()impl Greet for Person

Test vs Debug

FeatureTestDebug
PurposeCheck correctnessFind mistakes
WhenAfter writing codeWhen something fails
Tools#[test], assert_eq!println!, dbg!

Vector vs Hash Map

FeatureVectorHash Map
OrderKeeps insertion orderNo guaranteed order
AccessBy indexBy key
Use caseListsLookups

Lesson Summaries

Lesson 1: Vectors store lists of values.

Lesson 2: Strings store and manipulate text.

Lesson 3: Hash maps store key-value pairs.

Lesson 4: Iterators go through collections.

Lesson 5: Closures are short inline functions.

Lesson 6: Generics let you write flexible code.

Lesson 7: Traits define shared behaviour.

Lesson 8: Modules organise code.

Lesson 9: Tests check your code.

Lesson 10: Debugging finds and fixes mistakes.

Lesson 11: Lifetimes track reference validity.

Lesson 12: Smart pointers add abilities.

Lesson 13: Common mistakes include unhandled None and missing trait bounds.

Lesson 14: Best practices: use iterators, generics, traits, and modules.

Lesson 15: Combine collections, modules, and iterators in a market price checker.

End-of-Module Summary

Congratulations! You have finished Module Four of the Certified Rust Programming Expert course. You learned how to store many values with vectors, strings, and hash maps. You learned how to process them with iterators and closures. You learned how to write flexible code with generics and traits. You learned how to organise code with modules, check it with tests, and fix it with debugging. You also learned about lifetimes and smart pointers. You saw many examples from Nigeria and everyday life. You now know common mistakes and best practices. Most importantly, you can build complete programs that manage many values safely and efficiently. Keep practising, and you will become a Certified Rust Programming Expert!

Frequently Asked Questions

  1. What is a vector? A growable list of values of the same type.
  2. What is a hash map? A collection of key-value pairs.
  3. What is an iterator? An object that goes through items one by one.
  4. What is a closure? A short inline function.
  5. What is a generic? Code that works with many types.
  6. What is a trait? Shared behaviour that types can implement.
  7. What is a module? A group of related code.
  8. How do I write a test? Use #[test] and assert_eq!.
  9. How do I debug? Use println! and dbg!.
  10. What is a lifetime? How long a reference is valid.

Matching Exercises

Match the word to its definition.

WordDefinition
1. VectorA. Key-value storage.
2. Hash MapB. Short inline function.
3. IteratorC. Growable list.
4. ClosureD. Shared behaviour.
5. TraitE. Goes through items one by one.

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

Scenario-based Exercises

  1. Scenario: You want to store a list of student names. What do you use?
    Answer: A vector.
  2. Scenario: You want to look up a student’s score by name. What do you use?
    Answer: A hash map.
  3. Scenario: You want to double every number in a list. What do you use?
    Answer: An iterator with map.
  4. Scenario: You want to write one function that works for both numbers and text. What do you use?
    Answer: Generics.
  5. Scenario: You want to check if your function works correctly. What do you write?
    Answer: A test with #[test].

Group Activity

Title: “Build a Market Price Checker”

Instructions: In groups of 3–4, write a Rust program that stores market items and prices in a hash map. Let the user type an item name, and the program prints the price. Use a loop to let the user check many items. Use a module to organise the code. Share your program with the class.

Goal: Practice hash maps, modules, loops, and input.

Individual Activity

Task: Write a Rust program that creates a vector of your five favourite foods. Use a for loop to print each food. Then use an iterator to print only the foods with more than 5 letters.

Hint: Use filter and collect.

Mini Project

Project: “My To-Do List”

Write a Rust program that stores tasks in a vector. Add a function to add a task. Add a function to remove a task by index. Add a function to print all tasks. Use a module to organise the code. Add a test to check that adding a task works.

Example output:

  1. Do homework
  2. Buy milk
  3. Call grandma
  

Practical Assignment

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

  1. Creates a hash map of student names to scores.
  2. Adds at least five students.
  3. Prints each student and their score.
  4. Calculates and prints the average score.
  5. Finds and prints the highest score.
  6. Uses a module to organise the code.
  7. Writes a test to check the average calculation.

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

Key Takeaways

  • Vectors store lists. Hash maps store key-value pairs.
  • Strings store text.
  • Iterators and closures process collections cleanly.
  • Generics let you write flexible code.
  • Traits define shared behaviour.
  • Modules organise code.
  • Tests check your code.
  • Debugging finds and fixes mistakes.
  • Lifetimes track reference validity.
  • Smart pointers add abilities.
  • Practice and read error messages carefully.

Classroom Discussion Questions

  1. Why do we need collections?
  2. When would you use a vector instead of a hash map?
  3. How do iterators make code cleaner?
  4. Why are closures useful with iterators?
  5. How do generics help avoid repeating code?
  6. Why are traits important for shared behaviour?
  7. How do modules keep projects tidy?
  8. Why should you write tests?
  9. How do you debug a program effectively?
  10. What did Ada learn from the market list story?

Preparation for Module Five

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

  • Concurrency: running many tasks at once.
  • Threads and message passing.
  • Async programming basics.
  • Working with files and the file system.
  • Building command-line tools.
  • Building a complete real-world project.

To prepare, make sure you have completed the practical assignment and can write programs with collections, modules, and tests. Review your notes on vectors, hash maps, and iterators. Bring your curiosity!

See you in Module Five!


End of Module Four – 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.
→