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
- Regex example to match multiline string in Rust?
- How to replace a capture group using Rust regex?
- How to match digits with regex in Rust?
- How to use regex to match a double quote in Rust?
- How to convert the keys of a Rust HashMap to a vector?
- Yield example in Rust
- How to insert an element into a Rust HashMap if it does not already exist?
- Generator example in Rust
- How to match the end of a line in a Rust regex?
- How to replace all matches using Rust regex?
See more codes...