rust / beginner
Snippet
Error Handling with Result Type
Rust uses the Result type for error handling without exceptions. Result is an enum with two variants: Ok(T) for success containing a value, and Err(E) for failure containing an error message. This approach makes errors explicit and forces you to handle them. The compiler will warn you if you ignore a Result that could fail.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
fn divide(a: f64, b: f64) -> Result<f64, String> {if b == 0.0 {return Err(String::from("Division by zero"));}Ok(a / b)}fn main() {match divide(10.0, 0.0) {Ok(result) => println!("Result: {}", result),Err(e) => println!("Error: {}", e),}}
Breakdown
1
Result<f64, String>
Return type that can be either Ok with f64 or Err with String
2
return Err(String::from("Division by zero"));
Returns an error variant when dividing by zero
3
Ok(a / b)
Returns the successful result wrapped in Ok variant
4
match divide(10.0, 0.0)
Pattern matches to handle both success and failure cases