Error Handling (Result/Option)
Rust has no exceptions. Result<T, E> represents success or failure. Option represents presence or absence.
Result
fn divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 { Err(String::from("div by zero")) }
else { Ok(a / b) }
}
? Operator
fn read_file(path: &str) -> Result<String, io::Error> {
let mut f = File::open(path)?;
let mut s = String::new();
f.read_to_string(&mut s)?;
Ok(s)
}
Matching
match divide(10.0, 2.0) {
Ok(v) => println!("{}", v),
Err(e) => eprintln!("Error: {}", e),
}
Custom Errors
use thiserror::Error;
#[derive(Error, Debug)]
enum AppError {
#[error("IO error: {0}")]
Io(#[from] io::Error),
#[error("Not found: {0}")]
NotFound(String),
}
unwrap/expect
// Only for prototypes and tests
let val = result.unwrap();
let val = result.expect("must succeed");
Common Pitfalls
- Ignoring returned errors in Go or fighting the borrow checker in Rust.
- Premature optimization before profiling.
- Skipping tests for concurrent and error paths.
- Not reading standard library documentation.
Best Practices
- Follow language idioms (Go: explicit errors; Rust: ownership).
- Write table-driven tests.
- Use
go fmt/cargo fmtconsistently. - Keep functions small and focused.
Memory and Performance Notes
Result is 2-word enum — no heap allocation for Ok/Err discriminant.
Exercise
Chain file read + parse operations using ? operator. Define custom error enum with thiserror.
Hint: Use anyhow for applications, thiserror for libraries.
Summary
Practice these concepts in small programs before building production services.
Debugging Checklist
- Read the full error message.
- Reduce to minimal reproduction.
- Check types and return values.
- Add logging at decision points.
- Write a test that catches the bug.
Real-World Application
Production services combine these fundamentals with logging, metrics, and graceful degradation.
Further Reading
Official language documentation, effective guides, and mature open-source projects.
Additional Examples
Consider how this topic applies in a larger project:
// Break the problem into smaller functions
// Test each function independently
// Integrate incrementally
Working through variations of the examples above builds deeper understanding than reading alone.
Interview and Review Questions
- Explain the core concept of this topic in your own words.
- What happens when this code runs with edge-case input (empty, null, zero, max value)?
- How would you debug a bug related to this topic in production?
- What are the performance implications of the approach shown here?
- How does this feature compare to the equivalent in another language you know?
Related Topics in This Path
Review adjacent pages in the learning path before and after this one. Concepts build on each other — skipping ahead often leads to confusion when later pages assume mastery of earlier material.
Return to the section index if you need to fill gaps in prerequisite knowledge.
Tooling Tips
- Enable all compiler or analyzer warnings during development.
- Use version control with small, focused commits for each exercise.
- Pair reading with typing — reproduce every code example by hand.
- Run tests or compile after every change to catch errors early.
- Keep a personal notes file linking concepts to your own project experiences.