Skip to content

Instantly share code, notes, and snippets.

@hussachai
Created April 1, 2022 06:20
Show Gist options
  • Save hussachai/85b4ba146392a60208aeb04bf2f25bf7 to your computer and use it in GitHub Desktop.
Save hussachai/85b4ba146392a60208aeb04bf2f25bf7 to your computer and use it in GitHub Desktop.
Error Handling in Rust that Every Beginner should Know (Rust Way)
fn square(s: &str) -> Result<f64, ParseFloatError> {
s.parse::<f64>().map (|i| i * i)
}
fn calculate(x: &str, y: &str) -> Result<f64, ParseFloatError> {
let x2 = square(x)?;
let y2 = square(y)?;
Ok((x2 + y2).sqrt())
}
println!("{:?}", calculate("2", "2")); // Ok(2.8284271247461903)
println!("{:?}", calculate("2", "?")); // Err(ParseFloatError { kind: Invalid })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment