Introduction
Result is a predefined enum type is Rust which is used to define the outcome of an operation that can either succeed or fail.
Example
This is how we write Result.
enum Result<T, E> {
Ok(T),
Err(E),
}
Ok represents success of generic type T
Err represents error of generic type E
Below is a good example of Result.
fn safe_divide(numerator: i32, denominator: i32) -> Result<i32, &'static str> {
if denominator == 0 {
Err("Division by zero is not allowed.")
} else {
Ok(numerator / denominator)
}
}
fn main() {
match safe_divide(10, 2) {
Ok(result) => println!("Result = {}", result),
Err(err) => eprintln!("Error: {}", err),
}
match safe_divide(5, 0) {
Ok(result) => println!("Result = {}", result),
Err(err) => eprintln!("Error: {}", err),
}
}
This is the classic case of divide by zero error.
safe_divide is a function that takes two integers as input and returns Result.
If we have valid arguments, we'll get the result. Else we'll get an error.
Result = 5
Error: Division by zero is not allowed.
We can also use Result as the return type for a file read operation.
use std::{
fs::File,
io::{Error,Read}
};
fn read_file_content(file_path: &str) -> Result<String, Error> {
let file_result = File::open(file_path);
match file_result {
Ok(mut file) => {
let mut content = String::new();
match file.read_to_string(&mut content) {
Ok(_) => Ok(content),
Err(err) => Err(err),
}
}
Err(err) => {
Err(err)
}
}
}
fn main() {
match read_file_content("file.txt") {
Ok(content) => println!("File content: {}", content),
Err(err) => eprintln!("Error reading file: {}", err),
}
}
The code introduces lot of new syntax, but is self explanatory.
If file.txt is present in the project directory, we'll get back the contents. Else we'll get back the error.
Conclusion
Result type used everywhere, while handling APIs, in Console Apps, etc. and we'll also use it a lot more going forward. So see you again in another Rusty article. Cheers!