Rust Lesson 5: Error Handling With Result

Rust Lesson 5: Error Handling With Result featured illustration

πŸ“Ž This article includes 1 downloadable practice file ↓

⏱ 1 min read

πŸ“˜ Rust Beginner Course Β· Lesson 5 of 6

Advertisement
fn parse(line: &str) -> Result<(String, f64), RowError> {
    let f: Vec<&str> = line.split(',').collect();
    if f.len() < 5 { return Err(RowError::Missing); }
    let qty: f64 = f[3].trim().parse().map_err(|_| RowError::BadNumber(f[3].to_string()))?;
    let rate: f64 = f[4].trim().parse().map_err(|_| RowError::BadNumber(f[4].to_string()))?;
    Ok((f[1].to_string(), qty * rate))
}

Functions that can fail return Result<T, E>: Ok(value) or Err(error). The ? operator returns the error early. Option<T> (Some/None) replaces null.

⚠️ unwrap() crashes on errors. Fine for quick experiments; use match, ? or expect(“clear message”) in real code.

Code for this course follows standard, current syntax; we test JavaScript and PowerShell scripts before publishing, and R/Java/Rust examples are kept to core language features. Tell us if anything fails on your setup.

Practice

Run the project file with a broken line added to sales.csv and watch it skip that row.

Advertisement

πŸ“Ž Practice files for this article

Free to use for learning. Files with macros (.bas) are plain text β€” import them with Alt+F11 β†’ File β†’ Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong

Leave a Comment