Open In App

Rust – Multiple Error Types

Last Updated : 18 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, sometimes we have scenarios where there is more than one error type. In Rust, the way of handling errors is different compared to other Object Oriented / System languages. Rust specifically uses ‘Result’ for returning something. 

The Result <T, E> is basically an enum that has – Ok(T) and Err(E) as the two variants. Rust uses Ok and Err to return errors and it is its way of handling errors.

Syntax:

enum Result<T, E> 

{
  Ok(T),  //Ok refers to successful
  Err(E),  //Err refers to error value

}

Generally, the Result enum interacts with the Result type of enum only, and the Option enum also interacts with the Option enum only. In situations, where cross-interaction is needful i.e. Option <–> Result or Result <–> Option then Rust throws error. Error types are unwrapped in those instances.

Now we see the generation of an error when we define a null vector and pass it to a function:

Example 1:

Rust




// Rust program Generation of an error when
// we define a null vector and pass it to a function.
fn first_number(vec: Vec<&str>) -> i32 {
    let first = vec.first().unwrap();
    5 * first.parse::<i32>().unwrap()
}
 
fn main() {
    let num = vec!["10","25","50"];
    let stringslist = vec!["GFG ide", "GFG careers", "2022"];
 
    println!("Five times of the num in list: {}", first_number(num));
    println!("Five times of the num in list: {}", first_number(stringslist));
}


Output:

 

Explanation: 

In this example, we declared a function first_number which by default returns i32 type. Variable ‘first’ is declared and then unwrapped with the first element of the list in vector. And, then we multiply the first element five times and the output of 50 is displayed 

Along with that, we can see that Rust throws a panic error and returns an Err value signifying that it is a parse error while returning the option enum. It occurs due to parse::i<32> error.

Example 2:

Rust




// Rust program for Rust throws a panic error and returns
fn first_number(vec: Vec<&str>) -> i32 {
    let first = vec.first().unwrap();
    5 * first.parse::<i32>().unwrap()
}
 
fn main() {
    let num = vec!["10","25","50"];
    let emptyvector = vec![];
    println!("Five times of the num in list: {}", first_number(num));
 
    println!("Five times of the num in list: {}", first_number(emptyvector));
     
}


Output:

 

Explanation:

This example is a follow-up of example 1. But, here we can clearly see that Rust has panicked at the execution of the main. Here, Vec::first returns an Option enum when the input vector (empty vector) is empty.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads