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 match whitespace with a regex in Rust?
- How to convert a u8 slice to a hex string in Rust?
- How to replace strings using Rust regex?
- How to perform matrix operations in Rust?
- How to sort a Rust HashMap?
- How to use regex to match a double quote in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to convert a Rust slice of u8 to u32?
- How to find the first match in a Rust regex?
- How to remove an element from a Rust HashMap if a condition is met?
See more codes...