What are some common error handling techniques in Rust?

In Rust, there are several common techniques for handling errors:

  1. Result type: The Result type is a built-in type in Rust that can be used to represent the success or failure of a computation. It has two variants, Ok and Err, where Ok wraps a successful value and Err wraps an error value. You can use the ? operator to automatically return Err from the current function if a computation returns Err.
fn divide(x: i32, y: i32) -> Result<i32, String> { if y == 0 { return Err(String::from("division by zero")); } Ok(x / y) }
  1. unwrap and expect: These two methods can be used to extract the value from an Ok variant or panic if the variant is Err. unwrap will panic with a default message, while expect allows you to specify a custom message to be displayed when panicking.
let x = Ok::<i32, i32>(10); let y = x.unwrap(); // y = 10 let x = Err::<i32, i32>(-1); let y = x.expect("An error occurred"); // panics with the message "An error occurred"
  1. try! macro: The try! macro can be used to automatically return an Err variant from the current function if a computation returns an Err.
fn divide(x: i32, y: i32) -> Result<i32, String> { if y == 0 { return Err(String::from("division by zero")); } Ok(x / y) } let x = try!(divide(10, 2)); // x = 5 let y = try!(divide(10, 0)); // panics with the message "division by zero"
  1. match statement: The match statement can be used to explicitly handle the Ok and Err variants of a Result type.
let x = Ok::<i32, i32>(10); match x { Ok(val) => println!("The value is: {}", val), Err(err) => println!("An error occurred: {}", err), }
  1. .and_then() and .map_err(): These methods can be used to chain the operations that return Result values and handle the errors or success in a more elegant way.
let x = Ok::<i32, i32>(10); let y = x.and_then(|val| Ok(val * 2)); let z = y.map_err(|err| err * 2);
In Rust, it is also a common practice to use an error type that implements the std::error::Error trait, which allows to obtain a more detailed representation of the error, such as the source of the error and a more specific error message.