Rust – Using Option enum for Error Handling
Last Updated :
09 Nov, 2022
In Rust, while coding the focus is mainly on performance, safety, and concurrency. It specifically uses enums like Option<T> and Result<T> for handling errors. Option type in Rust generally denotes option values that have two attributes: Some and None. The option type creates an i32 box for using inner values.
Options <T> uses pattern matches for querying whether the value is present or not and in case there aren’t any, it references a nullable (None). Whenever there is a pattern match, the rust compiler assigns the box a value, and if there aren’t any then the box is empty.
Example 1:
Rust
#![allow(unused)]
fn main() {
let matching_digit = Some(100);
fn processing_digit(i: i32) {
println!( "Inside Processing digit function!" );
}
fn processing_other_digit(i: i32) {
println!( "Inside Processing Other digit function!" );
}
let msg = match matching_digit {
Some(x) if x < 20 => processing_digit(x),
Some(x) => processing_digit(x),
None => panic!(),
};
}
|
Output:
Explanation:
In this example, we have used a variable named matching_digit that holds a value passed by the Some() function. The function processing digit as well the function other_processing digit both accept 32-bit integers. Now, we pass a value of 100 and assign a condition to one of the Some parameters that if the value is less than 20 it will match and the processing_digit function would be called and if nothing is passed Rust will use None which would panic.
Example 2:
Rust
fn find(search: &str, variable: char ) -> Option<usize> {search.find(variable) }
fn main() {
let var_name = "GeeksforGeeks" ;
match find(var_name, 'G' ) {
None => println!( "Letter not found" ),
Some(_i) => println!( "Letter found" ),
}
}
|
Output:
Explanation:
In this example, we are finding the letter ‘G’ initially and we are checking using Some() whether the value is present or not. If it is present then var_name matches with the find function and we print Letter found in the output.
Similarly, for another example, if we search for the letter ‘Z’ we won’t find it.
Example 3:
Rust
fn find(search: &str, variable: char ) -> Option<usize> { search.find(variable) }
fn main() {
let var_name = "GeeksforGeeks" ;
match find(var_name, 'Z' ) {
None => println!( "Letter not found" ),
Some(_i) => println!( "Letter found" ),
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...