Rs
Module 3Result & LabLesson 7 of 920 min

Result Basics

Ok/Err for parsing prices and recoverable failures.

Result<T, E>

rust
enum Result<T, E> {
    Ok(T),
    Err(E),
}

Parse pipeline

rust
fn parse_px(s: &str) -> Result<f64, String> {
    s.parse().map_err(|e| format!("px parse: {e}"))
}

Design rule

  • Library code: return Result
  • main/UI: log or display Err
  • Panic: only on bugs, not bad user input

Exercise

Challenge

Parse "SYM,PX" into (String, f64) as Result.

Tips
  • map_err adds context
  • Bad market data is Err not panic
  • Result composes with ?

Try it live

Result BasicsRust 2021
Loading editor…
Output
Press Run to compile and execute.