Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Demonstrates basic error handling in Rust using
- the `Result` enum with `Ok` and `Err(e)`.
- */
- /// Divides two `f64` numbers and returns a `Result`:
- /// - `Ok(f64)` if the division succeeds
- /// - `Err(String)` if attempting to divide by zero
- fn divide(dividend: f64, divisor: f64) -> Result<f64, String> {
- if divisor == 0.0 {
- // Return an error wrapped in `Err`
- Err(String::from("Cannot divide by zero!"))
- } else {
- // Return a successful value wrapped in `Ok`
- Ok(dividend / divisor)
- }
- }
- fn main() {
- // 1. Success case (returns `Ok`)
- let result_1 = divide(10.0, 2.0);
- match result_1 {
- Ok(value) => println!("Success! Answer: {}", value),
- Err(e) => println!("Error: {}", e),
- }
- println!("----------------");
- // 2. Error case (returns `Err(e)`)
- let result_2 = divide(10.0, 0.0);
- match result_2 {
- Ok(value) => println!("Success! Answer: {}", value),
- Err(e) => println!("Error: {}", e),
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment