“Certified Rust Programming Expert” – A complete path from beginner to professional
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!
After finishing this module, you will be able to:
impl blocks.match with enums for pattern matching.Option and Result for error handling.unwrap, expect, and the ? operator safely.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.
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:
struct followed by the name (use PascalCase: Student).{ }.name: Type.Mini summary: A struct groups related data. It is like a card that holds many pieces of information about one thing.
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.
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:
impl StructName { }.fn method_name(&self) { }.&self means the method borrows the instance.instance.method_name().Mini summary: Methods are functions inside impl. They make structs powerful and clean.
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.
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.
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.
Option – Handling Missing ValuesDefinition: 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.
Result – Handling ErrorsDefinition: 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.
unwrap and expect – Quick but RiskyDefinition: 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 ?.
? Operator – Safe Error PropagationDefinition: 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.
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.
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.
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:
| Mistake | What happens | Rust’s help |
|---|---|---|
Forgetting to handle None | Compiler error | “non-exhaustive patterns” |
Using unwrap on None | Program panics | Runtime crash |
| Missing a field in struct | Compiler error | “missing field” |
| Wrong type in enum variant | Compiler error | “mismatched types” |
Forgetting &self in method | Compiler error | “expected &self” |
Forgetting to derive Debug | Cannot print struct | “doesn’t implement Debug” |
Mini summary: Rust catches many mistakes early. Read the error messages. They tell you exactly what to fix.
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:
match to handle all variants.Option for missing values, not null.Result for operations that can fail.unwrap in real programs.? to propagate errors cleanly.Debug for easy printing.Mini summary: Good habits make you a better programmer. Start them now.
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.
| Word | Simple Definition |
|---|---|
| Struct | A custom type that groups related data. |
| Field | A piece of data inside a struct. |
| Instance | A specific value created from a struct. |
| Method | A function that belongs to a struct. |
impl | A block where you define methods for a struct. |
| Enum | A type that can be one of several variants. |
| Variant | One of the possible choices in an enum. |
Option | An enum for values that may be missing: Some or None. |
Result | An enum for success or failure: Ok or Err. |
unwrap | Extracts value or panics if empty. |
expect | Like unwrap but with a custom message. |
? operator | Propagates errors cleanly. |
| Trait | An ability or behaviour that types can have. |
derive | Automatically adds traits to a struct or enum. |
| Panic | When a program crashes due to an unrecoverable error. |
impl.match handles all enum variants safely.Option: Handles missing values without null.Result: Handles operations that can fail.? operator: Propagates errors cleanly.Debug and Clone automatically.struct Name { }.field: Type.Name { field: value, ... }.instance.field.impl Name { }.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());
}
Result step by stepResult<T, E>.Ok(value) for success.Err(error) for failure.match to handle both cases.? to propagate the error.Example:
fn parse_age(s: &str) -> Result{ match s.parse:: () { Ok(age) => Ok(age), Err(_) => Err(String::from("Invalid age")), } }
Option step by stepSome(value) when there is a value.None when there is no value.match to handle both cases.if let Some(x) = ... for short handling.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"), }
Option for optional fields.Result for success or error.Option for signal strength.Result for success or failure.Option for gold or empty.Result for success or failure.Option for milk or no milk.Result for success or burnt.Option and Result are inspired by functional programming languages.Option.? operator is one of Rust’s most loved features.Debug is one of the most common things Rust programmers do.? operator can only be used in functions that return Result or Option.Result is used everywhere in real programs?Option prevents the famous “billion-dollar mistake” of null pointers?match can destructure structs and enums?#[derive(Debug)] lets you print your structs easily?? operator can be used in functions that return Result?Option and Result are just enums?impl.match handles all enum variants.Option handles missing values.Result handles errors.unwrap is quick but risky.? propagates errors cleanly.derive adds traits automatically.None or Err.unwrap on a value that might be missing.Debug before printing.&self in methods.match.Option instead of null.Result for fallible operations.unwrap in real programs.? to propagate errors.Debug for easy printing.cargo check often.
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();
Start
|
V
Value exists?
|
+-- Yes --> Some(value)
|
+-- No --> None
|
V
Match on Option
|
+-- Some(v) --> Use v
|
+-- None --> Handle missing
Start
|
V
Operation succeeded?
|
+-- Yes --> Ok(value)
|
+-- No --> Err(error)
|
V
Match on Result
|
+-- Ok(v) --> Use v
|
+-- Err(e) --> Handle error
?
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
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 🎉
| Feature | Struct | Enum |
|---|---|---|
| Purpose | Group related data | Represent choices |
| Example | Student { name, age } | Grade { A, B, C, F } |
| Fields | All fields exist together | Only one variant at a time |
| Use case | Data records | State machines, options |
| Feature | Option | Result |
|---|---|---|
| Purpose | Value may be missing | Operation may fail |
| Variants | Some, None | Ok, Err |
| Use case | Optional fields | File reading, parsing |
| Error info | No error details | Contains error details |
| Method | Safety | When to use |
|---|---|---|
unwrap() | Risky (panics) | Quick tests, prototypes |
match | Safe | When you need custom handling |
? | Safe | When you want to propagate errors |
| Feature | Struct | Method |
|---|---|---|
| What is it? | A data type | A function |
| Where defined? | struct Name { } | impl Name { } |
| Purpose | Hold data | Do something with data |
| Example | Student { name, age } | fn show(&self) |
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.
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!
Option? An enum for values that may be missing: Some or None.Result? An enum for success or failure: Ok or Err.unwrap? A method that extracts a value or panics.? operator? It propagates errors cleanly.derive? It automatically adds traits to a struct or enum.Option handles missing values safely.match.Match the word to its definition.
| Word | Definition |
|---|---|
| 1. Struct | A. A type that can be one of several variants. |
| 2. Enum | B. Groups related data. |
| 3. Method | C. Handles missing values. |
| 4. Option | D. Handles success or failure. |
| 5. Result | E. A function that belongs to a struct. |
Answers: 1-B, 2-A, 3-E, 4-C, 5-D
Option.Result.#[derive(Debug)].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.
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.
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
Assignment: Create a new Cargo project called bank_account. In main.rs, write a program that:
BankAccount struct with owner (String) and balance (f64).deposit(amount) and withdraw(amount) -> Result<(), String>.withdraw returns Err if there are insufficient funds.match to handle the Result from withdraw.Debug for the struct.Submit: Your main.rs file and a screenshot of the program running.
Option handles missing values.Result handles errors.unwrap is quick but risky.? propagates errors cleanly.derive adds traits automatically.Option instead of null?unwrap on None?? operator help with error handling?match important with enums?In Module Four, we will dive deeper into Rust. We will learn about:
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