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 ResultUse
std::fs::read_to_string inside read_username to read the fileUse the
? operator to propagate errors in read_usernameCall
read_username from main and handle the resultPrint 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