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

Module Three

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

Module Three: Custom Types and Error Handling – Building Your Own Data Safely

“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. Now it is time to build your own data types.

Imagine you are building a school management program. You need to store information about students: their names, ages, classes, and scores. If you use separate variables for each piece of information, your code will become a big, messy pile. Rust gives you a better way: structs and enums.

A struct groups related data together. An enum lets you choose one value from a list of possibilities. Together, they help you build clear, safe programs. We will also learn about error handling with Result and Option. These are Rust’s tools for handling things that might go wrong, without crashing.

By the end of this module, you will be able to design your own data types and write programs that handle errors gracefully. Let’s get started!

Learning Objectives

After finishing this module, you will be able to:

  • Define and use structs to group related data.
  • Add methods to structs using impl blocks.
  • Define and use enums to represent choices.
  • Use match with enums for pattern matching.
  • Understand Option and Result for error handling.
  • Use unwrap, expect, and the ? operator safely.
  • Write programs that handle errors without crashing.
  • Complete a mini project and practical assignment.

Warm-up Story: Tunde Builds a School Register

Tunde is a bright boy in Abuja. His teacher asked him to keep a register of all the students in his class. At first, Tunde used a separate notebook for each student. He wrote name in one book, age in another, and score in another. Soon, the books were everywhere. He mixed up names and scores. It was a mess!

Tunde’s friend, Ada, said, “Tunde, why don’t you use one card for each student? Write the name, age, and score on the same card. Then you can keep all cards in one box.”

Tunde tried it. It was much better! Each card held all the information about one student. He could look at a card and see everything at once. He could also write notes on the card, like “Good in Maths” or “Needs help in English.”

In Rust, that card is called a struct. It groups related data together. And the notes are like methods—actions you can do with the card.

But then Tunde faced another problem. Some students had not taken the exam yet. Their score was missing. Tunde could not write “0” because that would mean they failed. He needed a way to say “no score yet.” Ada said, “Use an Option. It can be Some(score) if there is a score, or None if there is no score.”

Tunde also needed to handle errors. What if a student’s name was written wrongly? What if the score was negative? Ada said, “Use a Result. It can be Ok(value) if everything is fine, or Err(error) if there is a problem.”

Tunde’s new register was clean, safe, and easy to use. Just like Rust!

Moral of the story: Grouping related data together makes programs clean and safe. Structs help us do that. And when data is missing or something goes wrong, Option and Result help us handle it without crashing.

Main Lessons

Lesson 1: What is a Struct?

Definition: A struct is a custom data type that groups related values together. Each value is called a field.

Why it is important: It keeps related data together, making code clean and easy to understand.

Simple explanation: Think of a student ID card. It has a name, age, class, and photo. All that information belongs to one student. A struct is like that card.

Real-life example: A bank account has a name, account number, and balance. All in one place.

School example: A student record with name, age, class, and score.

Home example: A recipe card with ingredients, steps, and cooking time.

Nigerian example: A market stall record with trader name, goods, price, and quantity.

Illustration:

  struct Student {
      name: String,
      age: u32,
      score: f64,
  }
  

Step-by-step:

  • Write struct followed by the name (use PascalCase: Student).
  • Open a block with { }.
  • List each field as name: Type.
  • Separate fields with commas.

Mini summary: A struct groups related data. It is like a card that holds many pieces of information about one thing.

Lesson 2: Creating and Using Struct Instances

Definition: An instance is a specific value created from a struct. You fill in the fields with actual data.

Why it is important: You need to create instances to use your structs in programs.

Simple explanation: The struct is the blank card. The instance is the card filled with a student’s details.

Real-life example: A blank form becomes an instance when you fill it with your name and address.

School example: A blank report card becomes an instance when it has your scores.

Home example: A shopping list becomes an instance when you write specific items.

Nigerian example: A blank POS receipt becomes an instance when it shows a transaction.

Illustration:

  let student1 = Student {
      name: String::from("Ada"),
      age: 13,
      score: 85.5,
  };

  println!("Name: {}", student1.name);
  println!("Age: {}", student1.age);
  println!("Score: {}", student1.score);
  

Mini summary: Create an instance by filling in the fields. Use dot notation to access fields.

Lesson 3: Methods – Actions on Structs

Definition: A method is a function that belongs to a struct. It is defined inside an impl block.

Why it is important: Methods let you do things with your data in a clean way.

Simple explanation: If the struct is a card, methods are actions you can do with the card, like “show details” or “update score.”

Real-life example: A phone has methods: call, send message, take photo.

School example: A student card has a method: “calculate grade.”

Home example: A TV remote has methods: turn on, change channel, volume up.

Nigerian example: A POS machine has methods: accept payment, print receipt.

Illustration:

  impl Student {
      fn show_details(&self) {
          println!("Name: {}, Age: {}, Score: {}", self.name, self.age, self.score);
      }

      fn is_pass(&self) -> bool {
          self.score >= 50.0
      }
  }
  

Step-by-step:

  • Write impl StructName { }.
  • Inside, write fn method_name(&self) { }.
  • &self means the method borrows the instance.
  • Call it with instance.method_name().

Mini summary: Methods are functions inside impl. They make structs powerful and clean.

Lesson 4: What is an Enum?

Definition: An enum (enumeration) is a type that can be one of several variants.

Why it is important: It represents choices clearly and safely.

Simple explanation: Think of a traffic light. It can be Red, Yellow, or Green. Those are the only choices. An enum lists all possible choices.

Real-life example: Days of the week: Monday, Tuesday, Wednesday, etc.

School example: Grades: A, B, C, D, F.

Home example: Light switch: On or Off.

Nigerian example: Payment methods: Cash, Transfer, Card, USSD.

Illustration:

  enum TrafficLight {
      Red,
      Yellow,
      Green,
  }

  enum PaymentMethod {
      Cash,
      Transfer,
      Card,
      USSD,
  }
  

Mini summary: Enums list possible choices. They make your code safe because you can only use the listed variants.

Lesson 5: Enums with Data

Definition: Enum variants can hold data. This makes enums very powerful.

Why it is important: Sometimes a choice comes with extra information.

Simple explanation: A payment can be Cash (with amount) or Card (with card number). The enum variant holds the data.

Real-life example: A message can be Text (with words), Image (with pixels), or Video (with frames).

School example: A result can be Pass (with score) or Fail (with reason).

Home example: A delivery can be Delivered (with time) or Pending (with expected date).

Nigerian example: A transfer can be Successful (with reference) or Failed (with error).

Illustration:

  enum Payment {
      Cash(f64),
      Transfer { bank: String, amount: f64 },
      Card(String),
  }
  

Mini summary: Enum variants can carry data. This lets you attach extra information to each choice.

Lesson 6: Pattern Matching with Enums

Definition: match works with enums to handle each variant.

Why it is important: It ensures you handle all possible variants safely.

Simple explanation: If the light is Red, stop. If Yellow, ready. If Green, go. match checks each variant.

Real-life example: A restaurant order: match the order to the kitchen action.

School example: Match the grade to a message: A -> Excellent, B -> Good, etc.

Home example: Match the weather to what to wear.

Nigerian example: Match the market day to the market location.

Illustration:

  let light = TrafficLight::Red;

  match light {
      TrafficLight::Red => println!("Stop!"),
      TrafficLight::Yellow => println!("Get ready..."),
      TrafficLight::Green => println!("Go!"),
  }
  

Mini summary: match with enums is safe and clean. Rust forces you to handle every variant.

Lesson 7: Option – Handling Missing Values

Definition: Option is an enum that can be Some(value) or None.

Why it is important: It handles cases where a value might be missing, without using null.

Simple explanation: Imagine a box that may or may not have a gift. Some(gift) means there is a gift. None means empty.

Real-life example: A phone contact that may or may not have an email address.

School example: A student may or may not have a middle name.

Home example: A fridge may or may not have milk.

Nigerian example: A market stall may or may not have tomatoes today.

Illustration:

  let some_number = Some(5);
  let no_number: Option = None;

  match some_number {
      Some(n) => println!("Number is {}", n),
      None => println!("No number"),
  }
  

Mini summary: Option handles missing values. Use Some and None. Always match both.

Lesson 8: Result – Handling Errors

Definition: Result is an enum that can be Ok(value) or Err(error).

Why it is important: It handles operations that might fail, like reading a file or parsing a number.

Simple explanation: Imagine you are baking. The cake might come out well (Ok) or burn (Err). Result tells you which happened.

Real-life example: An ATM withdrawal: Ok(cash) or Err("Insufficient funds").

School example: An exam: Ok(score) or Err("Absent").

Home example: A phone call: Ok("Connected") or Err("No network").

Nigerian example: A transfer: Ok("Successful") or Err("Network failure").

Illustration:

  fn divide(a: f64, b: f64) -> Result {
      if b == 0.0 {
          Err(String::from("Cannot divide by zero"))
      } else {
          Ok(a / b)
      }
  }

  match divide(10.0, 2.0) {
      Ok(result) => println!("Result: {}", result),
      Err(e) => println!("Error: {}", e),
  }
  

Mini summary: Result handles success and failure. Use Ok for success and Err for errors. Always handle both.

Lesson 9: unwrap and expect – Quick but Risky

Definition: unwrap() and expect() extract the value from Option or Result. If there is no value, the program panics (crashes).

Why it is important: They are quick for testing, but risky for real programs.

Simple explanation: Imagine opening a box. If there is a gift, you take it. If empty, you scream and fall down. That is unwrap.

Real-life example: Pressing an elevator button. If it works, fine. If not, you are stuck.

School example: Assuming you will pass without studying. If you fail, you panic.

Home example: Assuming there is fuel in the generator. If not, it stops.

Nigerian example: Assuming there is network before a transfer. If not, it fails.

Illustration:

  let x = Some(5);
  let y = x.unwrap(); // y = 5

  let z: Option = None;
  // let w = z.unwrap(); // PANIC! Program crashes
  

Mini summary: unwrap and expect are quick but dangerous. Use them only when you are sure there is a value. In real programs, use match or ?.

Lesson 10: The ? Operator – Safe Error Propagation

Definition: The ? operator returns the value if Ok, or returns the error if Err.

Why it is important: It makes error handling clean without match every time.

Simple explanation: If something works, continue. If it fails, pass the problem up to the caller.

Real-life example: A relay race. If a runner falls, the next runner takes over the problem.

School example: If you don’t understand a topic, ask the teacher. The teacher handles it.

Home example: If the remote is not working, give it to your dad. He fixes it.

Nigerian example: If the POS fails, the cashier calls the bank. The bank handles it.

Illustration:

  fn read_number() -> Result {
      let s = "42";
      let n: i32 = s.parse().map_err(|_| "Not a number".to_string())?;
      Ok(n)
  }
  

Mini summary: The ? operator propagates errors cleanly. Use it in functions that return Result.

Lesson 11: Structs with Methods and Enums Together

Definition: You can use structs and enums together to build powerful data models.

Why it is important: Real programs need both grouping and choices.

Simple explanation: A student struct with a field that is an enum for grade.

Real-life example: A car with a field for fuel type: Petrol, Diesel, Electric.

School example: A student with a field for result: Pass, Fail, Pending.

Home example: A delivery with a field for status: Ordered, Shipped, Delivered.

Nigerian example: A transaction with a field for payment method: Cash, Transfer, Card, USSD.

Illustration:

  enum Grade {
      A,
      B,
      C,
      F,
  }

  struct Student {
      name: String,
      age: u32,
      grade: Grade,
  }

  impl Student {
      fn show(&self) {
          println!("{} is {} years old", self.name, self.age);
          match self.grade {
              Grade::A => println!("Excellent!"),
              Grade::B => println!("Good job!"),
              Grade::C => println!("Keep trying!"),
              Grade::F => println!("Needs improvement."),
          }
      }
  }
  

Mini summary: Combine structs and enums for rich data. Use match to handle enum fields.

Lesson 12: Deriving Traits – Making Structs Useful

Definition: Traits are like abilities. Rust can automatically add some traits to your structs with #[derive(...)].

Why it is important: It saves you time and makes your structs work with printing, comparing, and cloning.

Simple explanation: Like a student automatically getting a library card when they join school. derive gives your struct automatic abilities.

Real-life example: A new phone automatically has calling and texting. You don’t build it from scratch.

School example: A new student automatically gets a uniform and timetable.

Home example: A new TV automatically has a remote.

Nigerian example: A new POS machine automatically accepts cards and prints receipts.

Illustration:

  #[derive(Debug, Clone, PartialEq)]
  struct Point {
      x: i32,
      y: i32,
  }

  let p1 = Point { x: 1, y: 2 };
  let p2 = p1.clone();
  println!("{:?}", p1); // Debug printing
  

Mini summary: #[derive(...)] adds traits like Debug, Clone, and PartialEq. It makes structs easier to use.

Lesson 13: Common Mistakes with Structs and Enums

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 fill a form correctly. Rust tells you what is missing.

Real-life example: Forgetting to sign a cheque. The bank rejects it.

School example: Forgetting to write your name on an exam. The teacher cannot mark it.

Home example: Forgetting to close the fridge. Food spoils.

Nigerian example: Forgetting to add the recipient’s name in a transfer. The money returns.

Table of common mistakes:

MistakeWhat happensRust’s help
Forgetting to handle NoneCompiler error“non-exhaustive patterns”
Using unwrap on NoneProgram panicsRuntime crash
Missing a field in structCompiler error“missing field”
Wrong type in enum variantCompiler error“mismatched types”
Forgetting &self in methodCompiler error“expected &self”
Forgetting to derive DebugCannot print struct“doesn’t implement Debug”

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

Lesson 14: Best Practices for Structs, Enums, and Errors

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 structs to group related data.
  • Use enums for choices.
  • Use match to handle all variants.
  • Use Option for missing values, not null.
  • Use Result for operations that can fail.
  • Avoid unwrap in real programs.
  • Use ? to propagate errors cleanly.
  • Derive Debug for easy printing.
  • Keep methods 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 structs, enums, methods, and error handling.

Program: Student Report Card

  #[derive(Debug)]
  enum Grade {
      A,
      B,
      C,
      F,
  }

  struct Student {
      name: String,
      age: u32,
      score: f64,
      grade: Grade,
  }

  impl Student {
      fn new(name: &str, age: u32, score: f64) -> Student {
          let grade = if score >= 70.0 {
              Grade::A
          } else if score >= 60.0 {
              Grade::B
          } else if score >= 50.0 {
              Grade::C
          } else {
              Grade::F
          };

          Student {
              name: String::from(name),
              age,
              score,
              grade,
          }
      }

      fn show(&self) {
          println!("Name: {}", self.name);
          println!("Age: {}", self.age);
          println!("Score: {}", self.score);
          match self.grade {
              Grade::A => println!("Grade: A (Excellent)"),
              Grade::B => println!("Grade: B (Good)"),
              Grade::C => println!("Grade: C (Average)"),
              Grade::F => println!("Grade: F (Fail)"),
          }
      }
  }

  fn main() {
      let s1 = Student::new("Ada", 13, 85.0);
      let s2 = Student::new("Tunde", 14, 45.0);

      s1.show();
      println!("---");
      s2.show();
  }
  

Explanation:

  • Grade is an enum with four variants.
  • Student is a struct with name, age, score, and grade.
  • new is a method that creates a Student and calculates the grade.
  • show is a method that prints the details and matches the grade.
  • main creates two students and shows their reports.

Mini summary: This program combines structs, enums, methods, and match. It is a complete example of what you can build.

Key Vocabulary

WordSimple Definition
StructA custom type that groups related data.
FieldA piece of data inside a struct.
InstanceA specific value created from a struct.
MethodA function that belongs to a struct.
implA block where you define methods for a struct.
EnumA type that can be one of several variants.
VariantOne of the possible choices in an enum.
OptionAn enum for values that may be missing: Some or None.
ResultAn enum for success or failure: Ok or Err.
unwrapExtracts value or panics if empty.
expectLike unwrap but with a custom message.
? operatorPropagates errors cleanly.
TraitAn ability or behaviour that types can have.
deriveAutomatically adds traits to a struct or enum.
PanicWhen a program crashes due to an unrecoverable error.

Important Concepts

  • Structs: Group related data into one type.
  • Methods: Functions that belong to a struct, defined in impl.
  • Enums: Represent choices with variants.
  • Pattern matching: match handles all enum variants safely.
  • Option: Handles missing values without null.
  • Result: Handles operations that can fail.
  • ? operator: Propagates errors cleanly.
  • Deriving traits: Adds abilities like Debug and Clone automatically.
  • Compiler as guard: Rust checks that you handle all cases.

Step-by-step Explanations

How to define and use a struct step by step

  1. Write struct Name { }.
  2. List fields as field: Type.
  3. Create an instance with Name { field: value, ... }.
  4. Access fields with instance.field.
  5. Add methods in impl Name { }.
  6. Call methods with instance.method().

Example:

  struct Book {
      title: String,
      author: String,
      pages: u32,
  }

  impl Book {
      fn summary(&self) -> String {
          format!("{} by {} ({} pages)", self.title, self.author, self.pages)
      }
  }

  fn main() {
      let b = Book {
          title: String::from("Things Fall Apart"),
          author: String::from("Chinua Achebe"),
          pages: 209,
      };
      println!("{}", b.summary());
  }
  

How to use Result step by step

  1. Write a function that returns Result<T, E>.
  2. Use Ok(value) for success.
  3. Use Err(error) for failure.
  4. Call the function and use match to handle both cases.
  5. Or use ? to propagate the error.

Example:

  fn parse_age(s: &str) -> Result {
      match s.parse::() {
          Ok(age) => Ok(age),
          Err(_) => Err(String::from("Invalid age")),
      }
  }
  

How to use Option step by step

  1. Use Some(value) when there is a value.
  2. Use None when there is no value.
  3. Use match to handle both cases.
  4. Or use if let Some(x) = ... for short handling.
  5. Avoid unwrap unless you are sure.

Example:

  fn find_student(name: &str) -> Option {
      if name == "Ada" {
          Some(13)
      } else {
          None
      }
  }

  match find_student("Ada") {
      Some(age) => println!("Age: {}", age),
      None => println!("Student not found"),
  }
  

Real-life Examples

  • Bank accounts: Struct with name, number, balance.
  • Traffic lights: Enum with Red, Yellow, Green.
  • Online forms: Option for optional fields.
  • File reading: Result for success or error.
  • Payment systems: Enum with Cash, Card, Transfer.

Nigerian Examples

  • POS transaction: Struct with amount, recipient, status.
  • Market stall: Struct with trader name, goods, prices.
  • Payment method: Enum with Cash, Transfer, Card, USSD.
  • Network status: Option for signal strength.
  • Bank transfer: Result for success or failure.

Fun Examples Children Can Relate To

  • Video game character: Struct with name, health, score.
  • Superpower: Enum with Flying, Invisibility, Strength.
  • Treasure box: Option for gold or empty.
  • Quest result: Result for success or failure.
  • Pet: Struct with name, type, age.

Everyday Examples

  • Contact list: Struct with name, phone, email.
  • Weather: Enum with Sunny, Rainy, Cloudy.
  • Fridge: Option for milk or no milk.
  • Cooking: Result for success or burnt.
  • Shopping list: Struct with item, quantity, price.

Parent Tips

  • Encourage your child to explain their structs out loud.
  • Let them make mistakes. Errors are learning opportunities.
  • Use everyday examples (contact list, weather) to explain structs and enums.
  • Set a small daily coding time. Consistency helps.
  • Celebrate small wins, like creating a working struct.
  • Be patient. Error handling 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 Option and Result are inspired by functional programming languages.
  • Rust has no null. Instead, it uses Option.
  • The ? operator is one of Rust’s most loved features.
  • Structs in Rust can have methods, unlike C structs.
  • Enums in Rust can hold data, unlike enums in many other languages.
  • Rust’s compiler forces you to handle every possible error.
  • Deriving Debug is one of the most common things Rust programmers do.
  • The ? operator can only be used in functions that return Result or Option.

Did You Know?

  • Did you know that Rust’s Result is used everywhere in real programs?
  • Did you know that Option prevents the famous “billion-dollar mistake” of null pointers?
  • Did you know that match can destructure structs and enums?
  • Did you know that #[derive(Debug)] lets you print your structs easily?
  • Did you know that the ? operator can be used in functions that return Result?
  • Did you know that enums can have methods too, just like structs?
  • Did you know that Option and Result are just enums?
  • Did you know that Rust’s compiler will not let you forget to handle an error?

Remember This

  • Structs group related data.
  • Methods are functions inside impl.
  • Enums represent choices.
  • match handles all enum variants.
  • Option handles missing values.
  • Result handles errors.
  • unwrap is quick but risky.
  • ? propagates errors cleanly.
  • derive adds traits automatically.
  • Rust’s compiler catches many mistakes before running.

Common Mistakes

  • Forgetting to handle None or Err.
  • Using unwrap on a value that might be missing.
  • Forgetting to derive Debug before printing.
  • Missing a field when creating a struct.
  • Using the wrong type in a struct field.
  • Forgetting &self in methods.
  • Not handling all enum variants in match.
  • Ignoring compiler error messages.

Best Practices

  • Use structs for related data.
  • Use enums for choices.
  • Use Option instead of null.
  • Use Result for fallible operations.
  • Avoid unwrap in real programs.
  • Use ? to propagate errors.
  • Derive Debug for easy printing.
  • Keep methods small and focused.
  • Write comments to explain why.
  • Run cargo check often.

Illustrations and Diagrams

Struct and Methods

  struct Student {
      name: String,
      age: u32,
      score: f64,
  }
        |
        V
  impl Student {
      fn show(&self) { ... }
      fn is_pass(&self) -> bool { ... }
  }
        |
        V
  let s = Student { ... };
  s.show();
  s.is_pass();
  

Option Flowchart

  Start
    |
    V
  Value exists?
    |
    +-- Yes --> Some(value)
    |
    +-- No  --> None
    |
    V
  Match on Option
    |
    +-- Some(v) --> Use v
    |
    +-- None    --> Handle missing
  

Result Flowchart

  Start
    |
    V
  Operation succeeded?
    |
    +-- Yes --> Ok(value)
    |
    +-- No  --> Err(error)
    |
    V
  Match on Result
    |
    +-- Ok(v)  --> Use v
    |
    +-- Err(e) --> Handle error
  

Error Propagation with ?

  Function A returns Result
        |
        V
  Calls Function B with ?
        |
        V
  If B returns Ok --> continue
        |
        V
  If B returns Err --> return Err to caller
        |
        V
  Caller handles error
  

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

Struct vs Enum

FeatureStructEnum
PurposeGroup related dataRepresent choices
ExampleStudent { name, age }Grade { A, B, C, F }
FieldsAll fields exist togetherOnly one variant at a time
Use caseData recordsState machines, options

Option vs Result

FeatureOptionResult
PurposeValue may be missingOperation may fail
VariantsSome, NoneOk, Err
Use caseOptional fieldsFile reading, parsing
Error infoNo error detailsContains error details

unwrap vs match vs ?

MethodSafetyWhen to use
unwrap()Risky (panics)Quick tests, prototypes
matchSafeWhen you need custom handling
?SafeWhen you want to propagate errors

Struct vs Method

FeatureStructMethod
What is it?A data typeA function
Where defined?struct Name { }impl Name { }
PurposeHold dataDo something with data
ExampleStudent { name, age }fn show(&self)

Lesson Summaries

Lesson 1: Structs group related data.

Lesson 2: Create instances by filling fields.

Lesson 3: Methods are functions inside impl.

Lesson 4: Enums represent choices.

Lesson 5: Enum variants can hold data.

Lesson 6: match handles all enum variants.

Lesson 7: Option handles missing values.

Lesson 8: Result handles success and failure.

Lesson 9: unwrap and expect are quick but risky.

Lesson 10: The ? operator propagates errors cleanly.

Lesson 11: Combine structs and enums for rich data.

Lesson 12: derive adds traits automatically.

Lesson 13: Common mistakes include unhandled None and missing fields.

Lesson 14: Best practices: use Option, Result, and avoid unwrap.

Lesson 15: Combine structs, enums, methods, and error handling in a student report program.

End-of-Module Summary

Congratulations! You have finished Module Three of the Certified Rust Programming Expert course. You learned how to build your own data types with structs and enums. You learned how to add methods to structs. You learned how to handle missing values with Option and errors with Result. You also learned the ? operator and how to derive traits like Debug. You saw many examples from Nigeria and everyday life. You now know common mistakes and best practices. Most importantly, you can design clean, safe programs that handle errors gracefully. Keep practising, and you will become a Certified Rust Programming Expert!

Frequently Asked Questions

  1. What is a struct? A custom type that groups related data.
  2. What is an enum? A type that can be one of several variants.
  3. What is a method? A function that belongs to a struct.
  4. What is Option? An enum for values that may be missing: Some or None.
  5. What is Result? An enum for success or failure: Ok or Err.
  6. What is unwrap? A method that extracts a value or panics.
  7. What is the ? operator? It propagates errors cleanly.
  8. What is derive? It automatically adds traits to a struct or enum.
  9. Why does Rust have no null? Because Option handles missing values safely.
  10. How do I handle all enum variants? Use match.

Matching Exercises

Match the word to its definition.

WordDefinition
1. StructA. A type that can be one of several variants.
2. EnumB. Groups related data.
3. MethodC. Handles missing values.
4. OptionD. Handles success or failure.
5. ResultE. A function that belongs to a struct.

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

Scenario-based Exercises

  1. Scenario: You want to store a student’s name, age, and score. What do you use?
    Answer: A struct.
  2. Scenario: You want to represent the days of the week. What do you use?
    Answer: An enum.
  3. Scenario: A user may or may not enter their middle name. What do you use?
    Answer: Option.
  4. Scenario: You are reading a file that might fail. What do you use?
    Answer: Result.
  5. Scenario: You want to print a struct for debugging. What do you add?
    Answer: #[derive(Debug)].

Group Activity

Title: “Build a School Management System”

Instructions: In groups of 3–4, design a Rust program that stores student information. Create a Student struct with name, age, and score. Create a Grade enum with A, B, C, F. Add a method to calculate the grade. Add a method to print the student details. Share your program with the class.

Goal: Practice structs, enums, methods, and match.

Individual Activity

Task: Write a Rust program that defines a Book struct with title, author, and pages. Add a method summary() that returns a string. Create two books and print their summaries.

Hint: Use format! to build the string.

Mini Project

Project: “My Contact List”

Write a Rust program that defines a Contact struct with name, phone, and email (email is Option<String>). Create a few contacts. Add a method to print the contact details. If email is None, print “No email”. Use match to handle the Option.

Example output:

  Name: Ada
  Phone: 08012345678
  Email: ada@example.com
  ---
  Name: Tunde
  Phone: 08087654321
  Email: No email
  

Practical Assignment

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

  1. Defines a BankAccount struct with owner (String) and balance (f64).
  2. Adds methods: deposit(amount) and withdraw(amount) -> Result<(), String>.
  3. withdraw returns Err if there are insufficient funds.
  4. Creates an account, deposits some money, tries to withdraw too much, and prints the result.
  5. Uses match to handle the Result from withdraw.
  6. Derives Debug for the struct.

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

Key Takeaways

  • Structs group related data.
  • Enums represent choices.
  • Methods add behaviour to structs.
  • Option handles missing values.
  • Result handles errors.
  • unwrap is quick but risky.
  • ? propagates errors cleanly.
  • derive adds traits automatically.
  • Rust’s compiler catches many mistakes early.
  • Practice and read error messages carefully.

Classroom Discussion Questions

  1. Why do we need structs?
  2. How are enums different from structs?
  3. Why does Rust have Option instead of null?
  4. What happens if you use unwrap on None?
  5. How does the ? operator help with error handling?
  6. Why is match important with enums?
  7. What traits can you derive for a struct?
  8. How do methods make structs more powerful?
  9. What did Tunde learn from the school register story?
  10. Where do you see structs and enums in Nigeria?

Preparation for Module Four

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

  • Collections: vectors, strings, and hash maps.
  • Iterators and closures.
  • Generics and traits.
  • Writing bigger, modular programs.
  • Testing and debugging.
  • Building a complete project.

To prepare, make sure you have completed the practical assignment and can write programs with structs, enums, and error handling. Review your notes on Option and Result. Bring your curiosity!

See you in Module Four!


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