rustHow to return error in Rust
Rust provides a number of ways to return errors. The most common way is to use the Result type. Result is an enum that can either be Ok or Err. Ok is used to indicate success and Err is used to indicate an error.
Code example:
fn divide(x: i32, y: i32) -> Result<i32, &'static str> {
if y == 0 {
return Err("Cannot divide by zero!");
}
Ok(x / y)
}
fn main() {
let result = divide(10, 0);
match result {
Ok(val) => println!("Result: {}", val),
Err(err) => println!("Error: {}", err),
}
}
Output
Error: Cannot divide by zero!
Explanation:
- The
dividefunction takes twoi32parameters and returns aResulttype. TheResulttype is an enum that can either beOkorErr. - If the second parameter is 0, the function returns an
Errwith the message "Cannot divide by zero!". - If the second parameter is not 0, the function returns an
Okwith the result of the division. - In the
mainfunction, the result of thedividefunction is stored in theresultvariable. - The
matchstatement is used to check the value of theresultvariable. - If the
resultisOk, the value is printed. - If the
resultisErr, the error message is printed.
Helpful links:
More of Rust
- How to use regex lookahead in Rust?
- How to replace strings using Rust regex?
- How to get size of pointer in Rust
- How to use Unicode in a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to use regex lookbehind in Rust?
- How to match a URL with a regex in Rust?
- How to use negation in Rust regex?
- How to ignore case in Rust regex?
- How to use the global flag in a Rust regex?
See more codes...