capypad
0 day streak
rust / beginner
Snippet

Result Type for Error Propagation

Result<T, E> is Rust's way of handling operations that can fail. Unlike Option<T> which represents potentially missing values, Result represents operations that can fail with an error. The Ok variant holds the success value, while Err holds error information.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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, 2.0) {
Ok(result) => println!("Result: {}", result),
Err(e) => println!("Error: {}", e),
}
let result = divide(5.0, 0.0).unwrap_or(-1.0);
println!("Safe result: {}", result);
}
Breakdown
1
Result<f64, String>
Return type indicating success (f64) or failure (String error)
2
return Err(String::from(...));
Returns an error wrapped in the Err variant
3
.unwrap_or(-1.0)
Extracts value or returns default if Err