Result Type in Rust Programming


There are two types of errors that occur in Rust, either a recoverable error or an unrecoverable error. We handle the unrecoverable errors with the help of panic!macro and the Result type along with others help in handling the recoverable errors.The Result type is a better version of the Option type which only describes the possible error instead of the possible absence.

Signature

The signature of Result Type is Result < T, E>and it can have only two outcomes.

These are:

  •  Ok(T): An element T was found.
  • Err(E): An error was found with an element E.

Rust also provides different methods that we can associate with the Result type. Mainly, we use the unwrap() method.

There are a few methods that return the Result type error, one of them is parse().

Example

Consider the example shown below −

fn multiply(first_number_str: &str, second_number_str: &str) -> i32 {
   let first_num = first_number_str.parse::().unwrap();
   let second_num = second_number_str.parse::().unwrap();
   first_num * second_num
}
fn main() {
   let twenty = multiply("10", "2");
   println!("double is {}", twenty);
   let tt = multiply("9", "2");
   println!("double is {}", tt);
}

Output

double is 20
double is 18

The above code works normally, as the numbers that we passed while invoking the functions are valid integers.

Now, consider changing one of the integers to something that is not an int, so that we encounter the Result type error.

Example

Consider the update code shown below:

fn multiply(first_number_str: &str, second_number_str: &str) -> i32 {
   let first_num = first_number_str.parse::().unwrap();
   let second_num = second_number_str.parse::().unwrap();
   first_num * second_num
}
fn main() {
   let twenty = multiply("10", "2");
   println!("double is {}", twenty);
   let tt = multiply("t", "2");
   println!("double is {}", tt);
}

Output

thread 'main' panicked at 'called `Result::unwrap()` on an `Err`
value: ParseIntError { kind: InvalidDigit }', src/main.rs:2:56
note: run with `RUST_BACKTRACE=1` environment variable to display
a backtrace
double is 20

Updated on: 03-Apr-2021

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements