Result
type: TheResult
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
andErr
, whereOk
wraps a successful value andErr
wraps an error value. You can use the?
operator to automatically returnErr
from the current function if a computation returnsErr
.
fn divide(x: i32, y: i32) -> Result<i32, String> { if y == 0 { return Err(String::from("division by zero")); } Ok(x / y) }
unwrap
andexpect
: These two methods can be used to extract the value from anOk
variant or panic if the variant isErr
.unwrap
will panic with a default message, whileexpect
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"
try!
macro: Thetry!
macro can be used to automatically return anErr
variant from the current function if a computation returns anErr
.
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"
match
statement: Thematch
statement can be used to explicitly handle theOk
andErr
variants of aResult
type.
let x = Ok::<i32, i32>(10); match x { Ok(val) => println!("The value is: {}", val), Err(err) => println!("An error occurred: {}", err), }
.and_then()
and.map_err()
: These methods can be used to chain the operations that returnResult
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.
Social Plugin