Created
April 1, 2022 06:20
-
-
Save hussachai/85b4ba146392a60208aeb04bf2f25bf7 to your computer and use it in GitHub Desktop.
Error Handling in Rust that Every Beginner should Know (Rust Way)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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