0
0
Rustprogramming~30 mins

Propagating errors with ? in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Propagating errors with ? in Rust
📖 Scenario: You are writing a small Rust program that reads a username from a file and prints it. Sometimes the file might not exist or be unreadable, so you need to handle errors properly.
🎯 Goal: Build a Rust program that reads the username from a file called username.txt and prints it. Use the ? operator to propagate errors instead of handling them manually.
📋 What You'll Learn
Create a function called read_username that returns a Result
Use std::fs::read_to_string inside read_username to read the file
Use the ? operator to propagate errors in read_username
Call read_username from main and handle the result
Print the username if reading is successful, or print an error message if it fails
💡 Why This Matters
🌍 Real World
Reading files and handling errors is common in programs that work with user data or configuration files.
💼 Career
Understanding error propagation with ? is essential for writing robust Rust applications in software development jobs.
Progress0 / 4 steps
1
Create the read_username function
Write a function called read_username that returns Result. Inside it, use std::fs::read_to_string to read the file "username.txt" and return the result directly.
Rust
Hint

Use fs::read_to_string("username.txt") and return it directly from the function.

2
Use the ? operator to propagate errors
Modify the read_username function to use the ? operator with fs::read_to_string to propagate errors instead of returning the result directly.
Rust
Hint

Use let username = fs::read_to_string("username.txt")?; and then return Ok(username).

3
Call read_username from main and handle errors
Write a main function that calls read_username. Use a match statement on the result to print the username if successful, or print Error reading username if there is an error.
Rust
Hint

Use match read_username() and print the username or an error message accordingly.

4
Print the username or error message
Run the program. It should print the username from username.txt if the file exists, or print Error reading username if it does not.
Rust
Hint

Make sure the file username.txt exists with content like Alice to see the username printed.