Functions in Rust which can fail return a Result:
Result<T, E>is the type used for returning and propagating errors. It is an enum with the variants,Ok(T), representing success and containing a value, andErr(E), representing error and containing an error value.
I highly recommend reading the Error Handling section in the Rust Book:
Rust has a number of features for handling situations in which something goes wrong
If you want to ignore an error, you have different possibilities:
-
Don’t use the
Result:let _ = failing_function();The function will be called, but the result will be ignored. If you omit
let _ =, you will get a warning. As of Rust 1.59, you can omit the let and just write_ = failing_function();. -
Ignore the
Errvariant ofResultusingif letormatch:if let Ok(ret) = failing_function() { // use the returned value }You may also convert the
ResultintoOptionwithResult::ok:let opt = failing_function().ok(); -
Unwrap the error. This code panics if an error occurred though:
let ret = failing_function().unwrap(); // or let ret = failing_function().expect("A panic message to be displayed");
try!() unwraps a result and early returns the function, if an error occurred. However, you should use ? instead of try! as this is deprecated.
See also:
- What is this question mark operator about?
- Is the question mark operator ? equivalent to the try! macro?
- How to do error handling in Rust and what are the common pitfalls?