0
0
Rustprogramming~30 mins

Error handling best practices in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Error handling best practices
📖 Scenario: You are building a simple Rust program that reads a username from a file and prints a greeting. Handling errors properly is important to make your program reliable and user-friendly.
🎯 Goal: Learn how to handle errors in Rust using Result, match, and the ? operator to write clean and safe code.
📋 What You'll Learn
Create a function to read a username from a file
Use a configuration variable for the filename
Handle errors using match and Result
Use the ? operator for error propagation
Print the greeting or an error message
💡 Why This Matters
🌍 Real World
Reading configuration or user data from files is common in many programs. Handling errors properly prevents crashes and helps users understand what went wrong.
💼 Career
Rust developers must write safe and reliable code. Understanding error handling with Result, match, and the ? operator is essential for building robust applications.
Progress0 / 4 steps
1
DATA SETUP: Create a function to read username from a file
Write a function called read_username that returns a Result. Inside, use std::fs::read_to_string to read from a file named "user.txt" and return the content.
Rust
Hint

Use std::fs::read_to_string("user.txt") to read the file content and return it directly.

2
CONFIGURATION: Add a variable for the filename
Create a variable called filename and set it to "user.txt". Update the read_username function to use this filename variable instead of the hardcoded string.
Rust
Hint

Define filename outside the function and use it inside read_username.

3
CORE LOGIC: Use match to handle errors when calling read_username
Call read_username() and use a match statement with variables username and error to handle the Ok and Err cases. In Ok, print "Hello, {username}!". In Err, print "Failed to read username: {error}".
Rust
Hint

Use match result with Ok(username) and Err(error) arms to print messages.

4
OUTPUT: Use the ? operator in read_username and print the greeting in main
Rewrite read_username to use the ? operator for error propagation. Then, in main, call read_username() and use match with variables username and error to print "Hello, {username}!" or "Failed to read username: {error}".
Rust
Hint

Use ? operator inside read_username to return errors quickly. Then handle the result in main with match.

Make sure the file user.txt contains Alice for testing.