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
divide
function takes twoi32
parameters and returns aResult
type. TheResult
type is an enum that can either beOk
orErr
. - If the second parameter is 0, the function returns an
Err
with the message "Cannot divide by zero!". - If the second parameter is not 0, the function returns an
Ok
with the result of the division. - In the
main
function, the result of thedivide
function is stored in theresult
variable. - The
match
statement is used to check the value of theresult
variable. - If the
result
isOk
, the value is printed. - If the
result
isErr
, the error message is printed.
Helpful links:
More of Rust
- How to use regex to match a double quote in Rust?
- Hashshet example in Rust
- How to split a string with Rust regex?
- How to get a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to use regex to match a group in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to replace all using regex in Rust?
- How to parse JSON string in Rust?
- How to use non-capturing groups in Rust regex?
See more codes...